我不知道这是否是正确的方法,但我认为它解释了我想要实现的目标。
我有三个向量:
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]);
所以我可以这样做:
std::rotate(v.begin(),v.begin+1,v.end())
and get:
v1 = 5, 2, 3
v2 = 8, 6, 7
v3 = 1, 9, 10
它几乎可以工作,执行以下操作会修改原始向量:
++v[0];
但赋值不起作用:
v[0] = new_value; // doesn't compile
Nor std::rotate
有什么影响。
我怎样才能做到这一点?
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;
}