Can anyone explain why isn’t the operator[] implemented for a std::list? I’ve searched around a bit but haven’t found an answer. It wouldn’t be too hard to implement or am I missing something?
Can anyone explain why isn’t the operator[] implemented for a std::list? I’ve searched around
Share
Retrieving an element by index is an O(n) operation for linked list, which is what
std::listis. So it was decided that providingoperator[]would be deceptive, since people would be tempted to actively use it, and then you’d see code like:which is O(n^2) – very nasty. So ISO C++ standard specifically mentions that all STL sequences that support
operator[]should do it in amortized constant time (23.1.1[lib.sequence.reqmts]/12), which is achievable forvectoranddeque, but notlist.For cases where you actually need that sort of thing, you can use
std::advancealgorithm: