0

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.

Eman
  • 165
  • 1
  • 1
  • 8

2 Answers2

3

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
dynamic
  • 46,985
  • 55
  • 154
  • 231
  • Thanks a lot for the answer. I get the idea behind it. However, it is a bit different from what I need. I have only one vector containing doubles and let's say it has the size of 1000 elements. I want to connect for example; the first 10 elements to the last 10 elements respectively. So when I change the first 10 elements, the last 10 elements also change. – Eman Apr 30 '16 at 09:43
  • @πάνταῥεῖ Thanks again. – Eman Apr 30 '16 at 10:50
  • You could also use emplace_back and make_shared `v1.emplace_back(make_shared());` – Andreas DM May 03 '16 at 20:12
0
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
Abdus Khazi
  • 453
  • 3
  • 17