c++pointersvectorreference

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!!!


Solution

  • 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;
    }