Is it possible to create a vector from elements of another vector so that changing an element by index in one of the vectors results in a change in the corresponding element in the second vector?
std::vector<double> temp_1 = {1, 4};
std::vector<double> temp_2;
temp_2.resize(3);
temp_2[0] = temp_1[1];
temp_2[1] = temp_1[0];
temp_1[0] = 55;
>>> temp_1 =[55,4]
>>> temp_2 =[4,55]
I can be done using pointers or reference wrappers, though note that any reallocation of the referenced vector will render the references invalid. However, if no reallocations are involved, it should be fine.
#include <vector>
#include <functional>
#include <iostream>
int main(int, char*[])
{
std::vector<int> x{1,2,3};
std::vector<std::reference_wrapper<const int>> y {
x[2], x[0], x[1]
};
std::cout << "y before modifying x\n";
for (auto el: y) {
std::cout << el << '\n';
}
x[1] = 8;
std::cout << "y after modifying x\n";
for (auto el: y) {
std::cout << el << '\n';
}
}