如何连接一个向量的两个元素?
问题描述:
我想知道如果在C ++中有一种方法连接一个向量的两个元素,例如std :: vector,如果一个被改变,其他的自动改变。
I would like to know if there is a way in C++ to connect two elements of a vector for example std::vector such that if one is changed, the other changes automatically. If not is there any other way to do so?
答
如果没有其他方法可以这样做?
解决方案
我们假设你有两个向量包含同一种类的实例 Object
。然后使用 shared_ptr< Object>
,您可以引用同一个对象:
Let's say you have two vectors containing instances of a same kind of Object
. Then using shared_ptr<Object>
you can refer to the same object:
vector<shared_ptr<Object>> v1;
vector<shared_ptr<Object>> v2;
for(int i=0;i<3;i++) {
v1.push_back(shared_ptr<Object>(new Object()));
v2.push_back(v1[i]);
}
现在,如果编辑一个向量的对象的属性,
Now if you edit a property of an object of one vector, the corresponding object will be updated too:
v1[0]->value = 12;
cout << v2[0]->value << endl; // print 12