Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make pointer/reference on element in vector?

I have two vectors and for some elements (not all) i need them to be connected ~ if i delete/change this element in one vector it should be removed/changed in both.

Something similar like pointers:

int r = 10;
int *p= &r;
*p = 3;

For example in next code it should change myvector2[0].a to 7.

#include <iostream>
#include <vector>

using namespace std;

struct elt {
    int a, b, c;
};

int main()
{

    vector<elt> myvector;
    vector <elt> myvector2;
    elt elt1 = {1,3,3};

    myvector.push_back(elt1);
    elt *elt2 = &elt1;
    myvector2.push_back(*elt2);

    myvector[0].a=7;

    cout << myvector[0].a << endl; //7
    cout << myvector2[0].a << endl; //1

    return 0;
}

How can i make this possible? Please help!!!

like image 488
dropky Avatar asked Jan 10 '23 06:01

dropky


2 Answers

As tgmath explained, the issue is that you wind up with two different objects in your vectors, as the standard containers store elements by value. I would recommend that you use shared pointers to properly maintain the lifetime of the objects (note this uses C++11 features):

#include <iostream>
#include <vector>
#include <memory>

struct elt {
    int a, b, c;
};

int main()
{
    std::vector<std::shared_ptr<elt>> myvector;
    std::vector<std::shared_ptr<elt>> myvector2;
    auto elt1 = std::make_shared<elt>(elt {1,3,3});

    myvector.push_back(elt1);
    myvector2.push_back(elt1);

    myvector[0]->a=7;

    std::cout << myvector[0]->a << std::endl; //7
    std::cout << myvector2[0]->a << std::endl; //7

    return 0;
}
like image 62
Dark Falcon Avatar answered Jan 18 '23 04:01

Dark Falcon


Pointers and references (and iterators) to elements of std::vector are invalidated whenever the vector reallocates, which can happen during insertion. So you can only keep these if the vector is guaranteed not to reallocate for the lifetime of the pointer/reference. This can be achieved if you don't insert into the vector, or if you call reserve() on it before you start (and before you acquire the pointer/reference/iterator), extending its capacity so that no reallocations will be necessary.

If you can't guarantee that, your only option is to keep the index instead of a pointer/reference. Of course, you will also need access to the vector itself for this to work, but you should be able to keep a pointer or reference to it, e.g.

typedef std::pair<std::vector<elt>*, size_t> ReferenceIntoVector;
like image 32
Angew is no longer proud of SO Avatar answered Jan 18 '23 03:01

Angew is no longer proud of SO