Split a vector into two equal parts in C++
Write an efficient code to split a vector into two equal parts in C++. If the vector contains an odd number of elements, the middle element may become a part of either vector.
1. Using middle iterator
A simple solution is to create two empty vectors and consider an iterator pointing to the vector’s middle element. Then the idea is to traverse the vector using iterators, and for each element, we check if it appears before the middle element or after the middle element in the vector. Based on the comparison result, the element goes into the first vector or the second vector. This approach is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> #include <vector> #include <iterator> #include <algorithm> void print(std::vector<int> v) { for (auto it = v.begin(); it != v.end(); ++it) { std::cout << *it << ' '; } std::cout << std::endl; } int main() { std::vector<int> v = { 1, 2, 3, 4, 5 }; std::vector<int> left; std::vector<int> right; std::vector<int>::iterator middleItr(v.begin() + v.size() / 2); for (auto it = v.begin(); it != v.end(); ++it) { if (std::distance(it, middleItr) > 0) { left.push_back(*it); } else { right.push_back(*it); } } print(left); print(right); return 0; } |
Output:
1 2
3 4 5
2. Using Vector Constructor
The recommended approach is to use the range constructor of the vector class, which can accept input iterators to the initial and final positions of another vector. We can use it, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> #include <iterator> #include <vector> void print(std::vector<int> v) { for (auto it = v.begin(); it != v.end(); ++it) { std::cout << *it << ' '; } std::cout << std::endl; } int main() { std::vector<int> v = { 1, 2, 3, 4, 5 }; std::vector<int> left(v.begin(), v.begin() + v.size() / 2); std::vector<int> right(v.begin() + v.size() / 2, v.end()); print(left); print(right); return 0; } |
Output:
1 2
3 4 5
That’s all about splitting a vector into two equal parts in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)