Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new C++ subvector?

Tags:

c++

vector

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?

like image 404
John Smith Avatar asked Mar 14 '12 15:03

John Smith


People also ask

How do you make a subvector?

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.

How do you copy a subvector?

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 .

What is a subvector?

subvector (plural subvectors) (mathematics) A subset of a vector (ordered tuple, or member of a vector space)


2 Answers

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); 
like image 172
hmjd Avatar answered Oct 21 '22 04:10

hmjd


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); 
like image 29
Flexo Avatar answered Oct 21 '22 03:10

Flexo