Reputation: 53
I've been studying how to make lists work in C++. Despite line 12 not working, I'm more interested in the line I mentioned in the title, as I do not understand what this does?
Consequently, there is an error in the for
loop, but I presume it's due to my lack of understanding of list<int>::iterator i;
, if anyone could break down and explain what this line means to me that'd be amazing!
#include <iostream>
#include <list>
using namespace std;
int main(){
list<int> integer_list;
integer_list.push_back(0); //Adds a new element to the end of the list.
integer_list.push_front(0); //Adds a new elements to the front of the list.
integer_list (++integer_list.begin(),2); // Insert '2' before the position of first argument.
integer_list.push_back(5);
integer_list.push_back(6);
list <int>::iterator i;
for (i = integer_list; i != integer_list.end(); ++i)
{
cout << *i << " ";
}
return 0;
}
This code was taken directly from here. Only the list's name has been changed.
Upvotes: 3
Views: 7594
Reputation: 1163
The list<int>::iterator
type is the iterator type for the templated class list<int>
. Iterators allow you to look at every element in a list one at a time. Fixing your code and trying to explain, this is the correct syntax:
for (i = integer_list.begin(); i != integer_list.end(); ++i)
{
// 'i' will equal each element in the list in turn
}
The methods list<int>.begin()
and list<int>.end()
each return instances of list<int>::iterator
that point to the beginning and end of the list, respectively. The first term in the for loop initialises your list<int>::iterator
to point to the beginning of the list using a copy-constructor. The second term checks to see if your iterator is pointing to the same place as the one set to point to the end (in other words, have you reached the end of the list yet) and the third term is an example of operator overloading. The class list<int>::iterator
has overloaded the ++
operator to behave like a pointer would: to point to the next item in the list.
You can also use a bit of syntactic sugar and use:
for (auto& i : integer_list)
{
}
for the same result. Hope this clears iterators up a bit for you.
Upvotes: 6