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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With