How to connect two elements of a vector?

自作多情 提交于 2019-12-12 01:54:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!