how to get part from the vector cpp
To get a part from a vector in C++, you can use the std::vector
member function std::vector::subvector
. Here's how you can do it:
- First, include the
<vector>
header file at the beginning of your code to use thestd::vector
container:
cpp
#include <vector>
- Create a
std::vector
object and populate it with some values:
cpp
std::vector<int> myVector = {1, 2, 3, 4, 5};
- Use the
std::vector::subvector
member function to get the desired part of the vector. Thesubvector
function takes two iterators as arguments, representing the range of elements you want to extract:
cpp
std::vector<int> sub = std::vector<int>(myVector.begin() + startIndex, myVector.begin() + endIndex);
In the above code, startIndex
is the index of the first element you want to include in the subvector, and endIndex
is the index of the element that comes after the last element you want to include.
- The resulting subvector will be stored in the
sub
variable, which you can then use as needed.
Here's a complete example that demonstrates getting a part from a vector:
#include <iostream>
#include <vector>
int main() {
std::vector<int> myVector = {1, 2, 3, 4, 5};
int startIndex = 1;
int endIndex = 4;
std::vector<int> sub = std::vector<int>(myVector.begin() + startIndex, myVector.begin() + endIndex);
for (int element : sub) {
std::cout << element << " ";
}
// Output: 2 3 4
return 0;
}
In this example, the subvector extracted from myVector
contains the elements at indices 1, 2, and 3, which are 2, 3, and 4 respectively. The code then prints these elements to the console.