简体   繁体   中英

Use pointers to items in a vector, and deleting items from the vector

I have std::vector of some class, and in my program I have some pointers to several items in the vector, the problem is when I delete one item, for example the first item, all pointers are wrong, this is an example of code:

vector<int> numbers;
numbers.push_back(100);
numbers.push_back(200);
numbers.push_back(300);

int *pNum = & numbers[1]; // pNum pointer to 200

numbers.erase(numbers.begin()); // now pNum pointer to 300

I understand why it happens, the question is whether there is a way to solve the problem?

You could use a node-based structure, such as an std::list . This guarantees that iterators other than those to erased elements remain valid.

The drawbacks are that you have no random access, and that the data aren't contiguous.

You can save pointers in the vector. This way, you separate the data from the vector, and your reference points to the real data.

vector<int*> numbers;

numbers.push_back(new int(100));
numbers.push_back(new int(200));
numbers.push_back(new int(300));

int * pNum  = numbers[1];

// memory leak!!!
numbers.erase( numbers.begin() );

cout << *pNum << endl;

It's safe, if you use c++11, to put shared_ptr s instead of raw pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM