Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traverse a List Using an Iterator?

Tags:

c++

stl

I need sample for traversing a list using C++.

like image 328
karthik Avatar asked Mar 29 '11 09:03

karthik


People also ask

Can an Iterator be used to traverse a linked list?

An Iterator can be used to loop through an LinkedList. The method hasNext( ) returns true if there are more elements in LinkedList and false otherwise.

Can an Iterator be used to traverse an ArrayList?

An Iterator can be used to loop through an ArrayList. The method hasNext( ) returns true if there are more elements in ArrayList and false otherwise.


2 Answers

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;   } 
like image 136
karthik Avatar answered Oct 02 '22 11:10

karthik


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 << " "; } 
like image 22
Pavel P Avatar answered Oct 02 '22 09:10

Pavel P