I need sample for traversing a list using C++.
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.
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.
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; }
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With