I need sample for traversing a list using C++.
Asked
Active
Viewed 7.0k times
28
-
Easy solution on Google'ing : http://www.java2s.com/Code/Cpp/List/TraverseaListUsinganIterator.htm – Saurabh Gokhale Mar 29 '11 at 09:29
-
25"now you're just being plain lazy" For all we know the poster may be an expert in some other programming language. If you don't want to help him, just don't. I was Googling 3 years later and found the answer very useful. – Travis Banger Jan 27 '14 at 18:34
4 Answers
32
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;
}

Saurabh Gokhale
- 53,625
- 36
- 139
- 164

karthik
- 17,453
- 70
- 78
- 122
-
Easy solution : http://www.java2s.com/Code/Cpp/List/TraverseaListUsinganIterator.htm – Saurabh Gokhale Mar 29 '11 at 09:29
20
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 << " ";
}

Pavel P
- 15,789
- 11
- 79
- 128
7
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;
}

Community
- 1
- 1

Oliver Charlesworth
- 267,707
- 33
- 569
- 680
-
1Although you should use `const_iterator` rather than `iterator` if you don't need to modify the list. – Mike Seymour Mar 29 '11 at 10:11
-