samedi 29 février 2020

How to link pointer to a std::vector element

I want to link a pointer to one of the data member of an std vector.

int main()
{
    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(4);
    vec.push_back(5);
    int *ip = &vec[2];
    std::cout << *ip << std::endl;
    vec.erase(vec.begin() + 1); 
    std::cout << *ip << std::endl;
    while (!_kbhit())
    {


    }
    std::cout << "Hello World!\n"; 
}

The issue which i am facing is that whenever i delete a data element from the vector the pointer than points to another data member.

How can i make a pointer to point at the same data member even after the vector resizes ?

Aucun commentaire:

Enregistrer un commentaire