Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a subvector from a vector without copy

I have a large size of vector and I want extract its subvector based on index. But I do not want to make a new copy of a subvector. Can I use pointer a iterator to return the pointer of the original vector?

something like:

vector<int> orig = { 0,1,2,3,4,5,6,7,8,9 };
vector<int> index = { 3,5,6,8 };
vector<int> dest (vector<int> orig, vector<int> index) 
{
   .... 
}

What I want get is get dest as { 3,5,6,8 } and it is point to orig but not the new copy. (index is the index vector of what I want to extract from the original vector)

Or, can I use smart pointer to do this?

like image 682
duqiyaner Avatar asked May 26 '15 21:05

duqiyaner


2 Answers

If you want the vector to be mutable, no. If you just want to pass a subvector around but not change the contents, why not change your various functions to take a start and end iterator rather than be passed a vector?

like image 115
Gabe Sechan Avatar answered Sep 18 '22 03:09

Gabe Sechan


Every time I say I've sworn off std::valarray, somebody brings up a problem like this that valarray supports quite directly. For example:

std::valarray<int> orig = { 0,1,2,3,4,5,6,7,8,9 };
std::valarray<size_t> index = { 3,5,6,8 };

orig[index] = -1;

Then if (for example) we print out the elements of orig with code like this:

for (int i=0; i<orig.size(); i++)
    std::cout << orig[i] << "\t";

... we get the following results:

0       1       2       -1      4       -1      -1      7       -1      9
like image 43
Jerry Coffin Avatar answered Sep 19 '22 03:09

Jerry Coffin