Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::list order guaranteed?

Is the order of the elements within an std::list guaranteed to remain in-order (unless, of course, a sort or something occurs)?

Moreover, is there any potentially undefined behavior with lists that might jumble them up?

I was/am under the impression that containers such as std::deque and the like are order-safe, but alas std::deque is not double-linked.

like image 926
Qix - MONICA WAS MISTREATED Avatar asked Oct 20 '12 09:10

Qix - MONICA WAS MISTREATED


People also ask

Is std::list ordered?

std::list::sort. Sorts the elements in ascending order. The order of equal elements is preserved.

Is list ordered in CPP?

The C++ function std::list::sort() sorts the elements of the list in ascending order. The order of equal elements is preserved.

Does sort work with list C++?

std::sort requires random access iterators and so cannot be used with list .

Should I use std::list?

Consider using std::list if: You need to store many items but the number is unknown. You need to insert or remove new elements from any position in the sequence. You do not need efficient access to random elements.


1 Answers

Yes the order is guaranteed in std::list. Since anything can happen with UB, mixing up the order of a std::list is possible (though unlikely I would think).

Short answer is that if your lists are not in the order you think they should be then the most likely reason is a bug in your program.

like image 194
john Avatar answered Sep 22 '22 10:09

john