To get a sub-vector in C++, you can use iterators or the std::vector
's begin()
and end()
functions with appropriate indices.
In this example,
vec
containing elements.std::vector
's begin()
and end()
functions with appropriate indices to create iterators.std::vector
's constructor that accepts iterators to create a new sub-vector named sub_vec
.sub_vec
to standard output.#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::vector<int> sub_vec(vec.begin() + 1, vec.begin() + 3);
for (int x : sub_vec) {
std::cout << x << " ";
}
return 0;
}
2 3
In this example,
vec
containing elements.std::vector
's begin()
and end()
functions with appropriate indices to create iterators.std::vector
's constructor that accepts iterators to create a new sub-vector named sub_vec
.sub_vec
to standard output.#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::vector<int> sub_vec(vec.begin() + 1, vec.end());
for (int x : sub_vec) {
std::cout << x << " ";
}
return 0;
}
2 3 4 5
In this tutorial, we learned How to get Sub Vector in C++ language with well detailed examples.