Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ creating subvector operating on same data

Hello I have a vector:

vector<int> myCuteVector {1,2,3,4};

Now I would like to create a subvector in such a way, that it would contain 2 first elements from myCuteVector in such a way that after modifying subvectors elements, elements of myCuteVector would change too.

Pseudo code:

vector<int> myCuteVector {1,2,3,4};
vector<int> myCuteSubVector = myCuteVector[0:2];
myCuteSubVector[0] = 5;
printf("%d", myCuteVector[0]) //would print also 5;

is it possible to achieve?

like image 589
Jakub Balicki Avatar asked Mar 18 '20 13:03

Jakub Balicki


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 sub vector?

Algorithm. Begin Initialize a vector v1 with its elements. Declare another vector v2 and copying elements of first vector to second vector using constructor method and they are deeply copied. Print the elements of v1.


2 Answers

You can do this with a std::reference_wrapper. That would look like:

int main()
{
    std::vector<int> myCuteVector {1,2,3,4};
    std::vector<std::reference_wrapper<int>> myCuteSubVector{myCuteVector.begin(), myCuteVector.begin() + 2};
    myCuteSubVector[0].get() = 5; // use get() to get a reference
    printf("%d", myCuteVector[0]); //will print 5;
}

Or you could just use iterators directly like

int main()
{
    std::vector<int> myCuteVector {1,2,3,4};
    std::vector<std::vector<int>::iterator> myCuteSubVector{myCuteVector.begin(), myCuteVector.begin() + 1};
    // it is important to note that in the constructor above we are building a list of
    // iterators, not using the range constructor like the first example
    *myCuteSubVector[0] = 5; // use * to get a reference
    printf("%d", myCuteVector[0]); //will print 5;
}
like image 153
NathanOliver Avatar answered Sep 26 '22 03:09

NathanOliver


Since C++20, you can use std::span:

std::vector<int> myCuteVector {1,2,3,4};
std::span<int> myCuteSubVector(myCuteVector.begin(), 2);
myCuteSubVector[0] = 5;
std::cout << myCuteVector[0];  // prints out 5

Live demo: https://wandbox.org/permlink/4lkxHLQO7lCq01eC.

like image 23
Daniel Langr Avatar answered Sep 24 '22 03:09

Daniel Langr