简体   繁体   中英

Regarding Lists in C++

list<int>::iterator it;
  for ( it = l.begin(); it != l.end(); it++ )
    cout << *it << " ";
  cout << endl;

Hi guys, can someone please explain what "lists do not allow random access" means for iterators? From my understanding, I believe it to mean that lists do not store memory in consecutive memory locations like arrays and vectors so you can't use the [] operator with lists, rather you have to traverse the entire list to find an element? If this is the case, how come you're allowed to increment the it iterator above?

Thanks so much!

The statement

lists do not allow random access

doesn't mean that you cannot access arbitrary (ie all) elements of a list. It typically means that you cannot access random elements of a list in the same time ("constant time" or O(1) is another thing you might see in this context). For instance, accessing the second element might be much faster (or slower) than accessing the 1002nd element.

The only way to access some arbitrary element is by starting at a well-defined position (eg begin() or rbegin() or some iterator you previously memorized) and then walking backwards or forwards one step at a time.

Contrast this with eg std::vector which allows you to access an arbitrary element much like with C arrays in "O(1) time" (ie it always takes the same time to access the element, no matter which element it is).

Lists in C++ are linked lists. That means that they don't store data in a consecutive memory block like an array of a vector does; instead, they consist of a number of nodes, each of whose has a link to the next and the previous node. The list itself only keeps links to the first and the last node. This allows inserting an element in the middle without computationally expensive reallocating and copying of other elements.

When you increment the iterator, you are basically just following the link to the next node of the list.

Because an iterator is not a pointer -- it just looks like one.

When you say ++it , that's merely a shorthand for it.operator++() . Inside that method, you can do anything you want. You are not required to merely add one to a pointer.

In the case of a list::iterator, it takes on the address of the next node in the list.

Well, somehow you´ve answered it yourself.

In a list, you can´t "jump" to random elements with [], all you can do
is to get the next one (compared to the current one where you are).

Starting at the first element and do something for each element until the end is no problem.
Do something for the first element, get the next one, do something, get the next one...

Each node contains address of the next node. By iterating you jump to the next node automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM