问题
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?
Thanks.
回答1:
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
回答2:
class A {
... Your class definition
public:
int x;
};
typedef std::shared_ptr<A> APtr;
typedef std::vector<APtr> AVect;
AVect v;
APtr ptr_a = std::make_shared<A>(); //using std::make_shared<> is better than naked new allocations in code.
v.push_back(ptr_a);
v.push_back(ptr_a);
v[0]->x = 3; //modifies v[1] as well
来源:https://stackoverflow.com/questions/36952849/how-to-connect-two-elements-of-a-vector