In C++, you can split a vector into smaller parts using iterators, algorithms, or by manually copying elements.
In this example,
data
containing elements.std::vector
's constructor with iterator range to split the vector.#include <iostream>
#include <vector>
int main() {
std::vector<int> data = {1, 2, 3, 4, 5, 6};
auto split_it = data.begin() + 3;
std::vector<int> left(data.begin(), split_it);
std::vector<int> right(split_it, data.end());
std::cout << "Left part: ";
for (auto& num : left) std::cout << num << ' ';
std::cout << '\n';
std::cout << "Right part: ";
for (auto& num : right) std::cout << num << ' ';
std::cout << '\n';
return 0;
}
Left part: 1 2 3 Right part: 4 5 6
In this example,
data
containing elements.std::partition
algorithm to partition the vector based on the predicate.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> data = {1, 2, 3, 4, 5, 6};
auto split_predicate = [](int x) { return x > 3; };
auto split_point = std::partition(data.begin(), data.end(), split_predicate);
std::vector<int> left(data.begin(), split_point);
std::vector<int> right(split_point, data.end());
std::cout << "Left part: ";
for (auto& num : left) std::cout << num << ' ';
std::cout << '\n';
std::cout << "Right part: ";
for (auto& num : right) std::cout << num << ' ';
std::cout << '\n';
return 0;
}
Left part: 1 2 3 Right part: 4 5 6
In this tutorial, we learned How to Split a Vector in C++ language with well detailed examples.