is there a built-in STL method to do that?
In java, there is list.subList(a,b) for extracting [a,b). Similar method in STL C++?
Getting a subvector from a vector in C++auto last = v. begin() + n + 1. Declare a variable vector of vector type. Pass the value of first and last position of vector.
“No” C++ is a statically-typed language. A vector will hold an object of a single type, and only a single type.
the int in vector is specifying its type. like in array when we declare array we specify its members types. int arrr[]; same case with vector(which is a dynamic array) so we have to specify its type to declare it.
The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.
Sure.
std::vector<int> subList(&originalVector[a], &originalVector[b]);
You can do:
#include <vector>
#include <cassert>
int main() {
std::vector<int> x;
for (int i=0; i<10; ++i) {
x.push_back(i);
}
// Here we create a copy of a subsequence/sublist of x:
std::vector<int> slice_of_x(x.begin() + 3, x.begin() + 7);
assert(slice_of_x.size() == 7-3);
assert(slice_of_x[0] == 3);
return 0;
}
This will make a copy of the requested part of x
. If you don't need a copy and would like to be more efficient, it might be preferable to pass around iterator (or pointer) pairs. That would avoid copying.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With