C++ 使用迭代器遍历列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5470331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:14:08  来源:igfitidea点击:

Traverse a List Using an Iterator?

c++stl

提问by karthik

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

我需要使用 C++ 遍历列表的示例。

回答by karthik

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

回答by Pavel P

To reflect new additions in C++ and extend somewhat outdated solution by @karthik, starting from C++11 it can be done shorterwith autospecifier:

为了反映 C++ 中的新增内容并扩展@karthik 有点过时的解决方案,从 C++11 开始,它可以使用auto说明符缩短

#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 easierusing range-based for loops:

或者更容易使用for循环基于范围的

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

回答by Oliver Charlesworth

If you mean an STL std::list, then here is a simple example from http://www.cplusplus.com/reference/stl/list/begin/.

如果您的意思是 STL std::list,那么这里有一个来自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;
}