Home > database >  How can I access an element erased from a c std::list?
How can I access an element erased from a c std::list?

Time:07-02

Suppose I have a c std::list object containing a few elements and an iterator it to one of the elements. How can I remove this element from the list but still be able to access it? In other words, I want it de-linked from the list, but not deallocated.

Curiously, using list::erase does seem to achieve this:

#include <iostream>
#include <cstdio>
#include <list>

using namespace std;

int main() {
    std::list<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);
    auto it = (--a.end());
    a.erase(it);
    cout << *it << endl;   /// outputs '3' anyway, without any error
}

But I assume this isn't really safe?

Questions:

  1. Is it a guarantee behavior that an element erased by list::erase is still accessible by the original iterator?

  2. If yes, how can I deallocate its memory?

  3. If no, how can I erase some element without deallocating its memory and be able access it after erasal?

CodePudding user response:

This can be done provided you don't mind using a second list to receive the erased item

auto it = (--a.end());
std::list<int> b;
b.splice(b.end(), a, it);
cout << *it << endl;   /// outputs '3'

splice removes the it element from list a and adds it to the end of list b. It's a constant time operation and does not invalidate any iterators.

  • Related