In this C++ tutorial, you shall learn how to split a vector into two halves (equal halves if even sized), with example programs.
Split Vector into two halves in C++
To split a vector into two halves, equal length halves if the length is even or nearly equal if the length is odd, we can use vector iterators vector::begin(), vector::size(), and vector::end() iterators as shown the following code snippet.
The code to split a vector v
into two vectors v1
and v2
of equal lengths or nearly equal lengths is
vector<string> v1 (v.begin(), v.begin() + v.size()/2);
vector<string> v2 (v.begin() + v.size()/2, v.end());
The first vector is from beginning to mid way of the original vector. The second vector is from mid way to end of the original vector.
For example, if {"apple", "banana", "avocado", "fig" }
is given vector, we can split this vector into two vectors { "apple", "banana"
} and { "avocado", "fig" }
.
C++ Program
In the following program, we take a vector in v
and split this into two equal halves v1
and v2
.
main.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
//string vector
vector<string> v { "apple", "banana", "avocado", "fig" };
//split vector into two halves
vector<string> v1 (v.begin(), v.begin() + v.size()/2);
vector<string> v2 (v.begin() + v.size()/2, v.end());
//print result vector
cout << "First Half" << endl;
for ( auto& element : v1 ) {
cout << element << " ";
}
cout << endl << endl << "Second Half" << endl;
for ( auto& element : v2 ) {
cout << element << " ";
}
}
Output
First Half
apple banana
Second Half
avocado fig
Conclusion
In this C++ Tutorial, we learned how to split given vector into two halves.