Traverse a List Using an Iterator?
To reflect new additions in C++ and extend somewhat outdated solution by @karthik, starting from C++11 it can be done shorter with auto specifier:
#include <iostream>
#include <list>
using namespace std;
typedef list<int> IntegerList;
int main()
{
IntegerList intList;
for (int i=1; i<=10; ++i)
intList.push_back(i * 2);
for (auto ci = intList.begin(); ci != intList.end(); ++ci)
cout << *ci << " ";
}
or even easier using range-based for loops:
#include <iostream>
#include <list>
using namespace std;
typedef list<int> IntegerList;
int main()
{
IntegerList intList;
for (int i=1; i<=10; ++i)
intList.push_back(i * 2);
for (int i : intList)
cout << i << " ";
}
If you mean an STL std::list
, then here is a simple example from http://www.cplusplus.com/reference/stl/list/begin/.
// list::begin
#include <iostream>
#include <list>
int main ()
{
int myints[] = {75,23,65,42,13};
std::list<int> mylist (myints,myints+5);
std::cout << "mylist contains:";
for (std::list<int>::iterator it=mylist.begin(); it != mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
The sample for your problem is as follows
#include <iostream>
#include <list>
using namespace std;
typedef list<int> IntegerList;
int main()
{
IntegerList intList;
for (int i = 1; i <= 10; ++i)
intList.push_back(i * 2);
for (IntegerList::const_iterator ci = intList.begin(); ci != intList.end(); ++ci)
cout << *ci << " ";
return 0;
}