Hi
Is the following safe ?
list<sth>::iterator it = myList . begin();
while ( *it != myList.end() )
myList . erase ( it ++ );
great thanks for help
Hi Krzysztof
There is a typo in your code:
while ( it != myList.end() )
I have no reason your code isn't safe, but if you want
to erase a list, there are two better ways:
MyList.erase(MyList.begin(), MyList.end());
or
MyList.clear();
Under Visual Studio 2008, the performance of erasing a range of
iterators
or to clear a list is much better. try the following code:
#include <list>
#include <iostream>
int main()
{
using namespace std;
list<int> L;
for (int i = 0; i < 1000 * 1000; ++i)
L.push_back(i);
list<int>::iterator it = L.begin();
L.erase(L.begin(), L.end()); // 1
while (*it != L.end()) // 2
L.erase(it++);
L.clear(); // 3
cout << "Done ... " << L.size() << '\n';
return 0;
}
Regards,
-- Saeed Amrollahi