I need sample for traversing a list using C++.
Asked
Active
Viewed 6.9k 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
- 51,864
- 34
- 134
- 163
karthik
- 17,006
- 70
- 76
- 122
-
Easy solution : http://www.java2s.com/Code/Cpp/List/TraverseaListUsinganIterator.htm – Saurabh Gokhale Mar 29 '11 at 09:29
19
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
- 14,808
- 11
- 74
- 115
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
- 260,367
- 30
- 546
- 667
-
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
-