28

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

RobH
  • 3,199
  • 1
  • 22
  • 27
karthik
  • 17,453
  • 70
  • 78
  • 122
  • 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 Answers4

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
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
0

now you can just use this:


#include <iostream>
#include <list>
using namespace std;

int main()
{
    list<int> intList;
    for (int i = 1; i <= 10; ++i)
        intList.push_back(i * 2);
    for (auto i:intList)
        cout << i << " ";
    return 0;
}
Kargath
  • 450
  • 5
  • 15