Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the order of clearing elements from std::list?

Tags:

c++

list

stl

I want to clear the contents of some std::list. The order of removing of elements is important for me. According to output of the following test program, the order is from first to last element. Is it guaranteed to be so? It was not clear for me from C++2003 standard.

#include <list>
#include <iostream>

struct A
{
  A(int i) : I(i) {}
  ~A() { std::cout << I << std::endl; }
  int I;
};

int main()
{
  std::list<A> l;
  l.push_back(A(1));
  l.push_back(A(2));
  l.push_back(A(3));

  std::cout << "clearing list" << std::endl;
  l.clear();
}

ideone link

like image 586
ks1322 Avatar asked Mar 23 '12 14:03

ks1322


People also ask

Is std::list ordered?

std::list<T,Allocator>::sort. Sorts the elements in ascending order. The order of equal elements is preserved. The first version uses operator< to compare the elements, the second version uses the given comparison function comp .

How do you clear a list in C++?

list::clear() is an inbuilt function in C++ STL which is declared in header file. list::clear(), clears the whole list. In other words the clear() removes all the elements present in the list container and leaves the container with size 0.

Does list have order in C++?

Description. The C++ function std::list::sort() sorts the elements of the list in ascending order. The order of equal elements is preserved. It uses operator< for comparison.


3 Answers

No, it's not defined, and you should not rely on it.

like image 70
Cat Plus Plus Avatar answered Oct 13 '22 00:10

Cat Plus Plus


No it is not defined.

The standard only specifys that whenever you call a.clear() it will be resolved as a.erase(q1,q2) and it just specify's the erase will erase all the elements in the range [q1,q2) but it does not specify the order in which it will do so.

like image 22
Alok Save Avatar answered Oct 12 '22 22:10

Alok Save


Just for completeness, the C++11 standard does not determine the order of destruction of any sequence containers, of which std::list is a member. It only states that all the elements are destroyed, all references, pointers and iterators referring to the elements are invalidated, and the past the end iterator may be invalidated. Concerning clear(), it makes no mention of erase(), begin() or end(), unlike hte C++03 standard.

like image 24
juanchopanza Avatar answered Oct 13 '22 00:10

juanchopanza