c++ creating subvector operating on same data

Viewed 179

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?

3 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;
}

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.

You can use pointers: -

vector<int> myCuteVector = {1,2,3,4};
vector<int*> myCuteSubVector;
for(int i = startPos; i < endPos; ++i)
    myCuteSubVector.emplace_back(&myCuteVector[i]);    //or you can use push_back()

Where startPos and endPos(excluding) specifies the indices from the original array which you want to change...

Then, to change value at position 'j'(which should be between [startPos, endPos)) with respect to the original array: -

*myCuteSubVector[j - startPos] = 123;

Of course, in your very specific case, you can simply write like this: -

vector<int> myCuteVector = {1,2,3,4};
vector<int*> myCuteSubVector = {&myCuteVector[0], &myCuteVector[1]};
*myCuteSubVector[0] = 5;

Not sure though why you would want to do this...

Related