To slice a vector in C++, you can use iterators or standard algorithms like std::copy or std::vector::assign to create a new vector with the desired elements.
In this example,
v1
containing some elements.std::vector
with the iterator range to create a new vector containing the sliced elements.// Slice a vector by iterator range
#include <iostream>
#include <vector>
int main() {
std::vector<int> v1 = {1, 2, 3, 4, 5};
auto start = v1.begin() + 1;
auto end = v1.begin() + 4;
std::vector<int> sliced_v1(start, end);
for (auto& elem : sliced_v1) {
std::cout << elem << " ";
}
return 0;
}
2 3 4
In this example,
v2
containing some elements.v2
to sliced_v2
that satisfy the condition.// Slice a vector by logical condition
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v2 = {1, 2, 3, 4, 5};
std::vector<int> sliced_v2;
auto condition = [](int x) { return x > 2; };
std::copy_if(v2.begin(), v2.end(), std::back_inserter(sliced_v2), condition);
for (auto& elem : sliced_v2) {
std::cout << elem << " ";
}
return 0;
}
3 4 5
In this tutorial, we learned How to Slice a Vector in C++ language with well detailed examples.