Why is it so slow iterating over a big std::list?

后端 未结 6 2067
生来不讨喜
生来不讨喜 2020-12-30 18:08

As title suggests, I had problems with a program of mine where I used a std::list as a stack and also to iterate over all elements of the list. The program was taking way to

6条回答
  •  醉梦人生
    2020-12-30 18:50

    [Edit: I stand corrected. std::list doesn't have operator[]. Sorry.]

    It's hard to tell from your description, but I suspect you were trying to access the items randomly (i.e., by index):

    for(int i = 0; i < mylist.size(); ++i) { ... mylist[i] ... }
    

    Instead of using the iterators:

    for(list::iterator i = mylist.begin(); i != mylist.end(); ++i) { ... (*i) ... }
    

    Both "vector" & "deque" are good at random access, so either will perform adequately for those types---O(1) in both cases. But "list" is not good at random access. Accessing the list by index would take O(n^2) time, versus O(1) when using iterators.

提交回复
热议问题