使用迭代器遍历列表?

问题描述 投票:0回答:5

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

c++ stl
5个回答
32
投票

您的问题的示例如下

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

20
投票

为了反映 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 << " ";
}

或者更容易使用基于范围的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 << " ";
}

7
投票

如果您指的是 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;
}

0
投票

现在你可以使用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
投票

这里我使用

while
来遍历,使用
next
来递增迭代器

#include <iostream>
#include<list>

int main() {
    std::list<int> nums({1,2,3,4,5,6,7,8,9});
    std::list<int>::iterator it = nums.begin();
    while (it != nums.end()) {
        std::cout << *it <<std::endl;
        it = next(it,1);
    }
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.