开发者

Traverse a List Using an Iterator?

I need sample for tr开发者_Go百科aversing a list using C++.


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 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;
}


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜