Say I have a vector with values [1,2,3,4,5,6,7,8,9,10]. I want to create a new vector that refers to, for example, [5,6,7,8]. I imagine this is just a matter of creating a vector with pointers or do I have to push_back all the intermediary values I need?
Getting a subvector from a vector in C++ Begin Declare s as vector s(vector const &v, int m, int n) to initialize start and end position of vector to constructor. auto first = v. begin() + m. auto last = v.
Use the copy() Function to Extract a Subvector From a Vector Firstly we declare a sub_vec variable with some elements to be copied. Next, we pass the original vector range as arguments to the copy() function and the begin iterator to the destination vector .
subvector (plural subvectors) (mathematics) A subset of a vector (ordered tuple, or member of a vector space)
One of std::vector
's constructor accepts a range:
std::vector<int> v; // Populate v. for (int i = 1; i <= 10; i++) v.push_back(i); // Construct v1 from subrange in v. std::vector<int> v1(v.begin() + 4, v.end() - 2);
This is fairly easy to do with std::valarray
instead of a vector:
#include <valarray> #include <iostream> #include <iterator> #include <algorithm> int main() { const std::valarray<int> arr={0,1,2,3,4,5,6,7,8,9,10}; const std::valarray<int>& slice = arr[std::slice(5, // start pos 4, // size 1 // stride )]; }
Which takes a "slice" of the valarray, more generically than a vector.
For a vector you can do it with the constructor that takes two iterators though:
const std::vector<int> arr={0,1,2,3,4,5,6,7,8,9,10}; std::vector<int> slice(arr.begin()+5, arr.begin()+9);
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