c++ creating subvector operating on same data
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.