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:

Download  Run Code

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:

Download  Run Code

Output:

1 2
3 4 5

That’s all about splitting a vector into two equal parts in C++.