I don't know if this is the right approach, but I think it explains what I'm trying to achieve.
I have three vectors:
std::vector<int> v1 = {1,2,3};
std::vector<int> v2 = {5,6,7};
std::vector<int> v3 = {8,9,10};
I would like to create a vector that contains references to the first elements of these vectors, I've tried doing it as follows:
std::vector<std::reference_wrapper<int>> v;
v.push_back(v1[0]);
v.push_back(v2[0]);
v.push_back(v3[0]);
so I could do:
std::rotate(v.begin(),v.begin+1,v.end())
and get:
v1 = 5, 2, 3
v2 = 8, 6, 7
v3 = 1, 9, 10
it almost works, doing the following modifies the original vectors:
++v[0];
But assignment doesn't work:
v[0] = new_value; // doesn't compile
Nor std::rotate
has any affect.
How could I make this work?
Code
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
void print_vector(std::vector<int> &v) {
std::for_each(v.begin(),v.end(),[](auto& x){std::cout << x << " ";});
std::cout << "\n";
}
int main() {
std::vector<int> v1 = {1,2,3};
std::vector<int> v2 = {5,6,7};
std::vector<int> v3 = {8,9,10};
std::vector<std::reference_wrapper<int>> v;
v.push_back(v1[0]);
v.push_back(v2[0]);
v.push_back(v3[0]);
// This doesn't work, it rotates the references but not the values
std::rotate(v.begin(),v.begin()+1,v.end());
print_vector(v1);
print_vector(v2);
print_vector(v3);
// Never the less this does work
++v[0];
print_vector(v1);
print_vector(v2);
print_vector(v3);
//v[0] = 3; // Assigment doesn't compile
return 0;
}