2011-03-29 115 views
26

我需要使用C++遍历列表的示例。使用迭代器遍历列表?

+0

简单的解决方案在谷歌” ing:http://www.java2s.com/Code/Cpp/List/TraverseaListUsinganIterator.htm – 2011-03-29 09:29:54

+22

“现在你只是懒惰懒惰”对于所有的w e知道海报可能是某种其他编程语言的专家。如果你不想帮助他,就不要。我3年后Google搜索,发现答案非常有用。 – 2014-01-27 18:34:45

+1

为什么OP和同一个人接受的答案? – Viet 2017-05-02 20:56:35

回答

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

简单的解决方案:http://www.java2s.com/Code/Cpp/List/TraverseaListUsinganIterator.htm – 2011-03-29 09:29:25

+0

Omg,这是否值得被问及?哪里有参考? RTFM! – Viet 2017-05-02 20:55:58

6

如果你的意思是一个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; 
} 
+1

尽管如果你不需要修改列表,你应该使用'const_iterator'而不是'iterator'。 – 2011-03-29 10:11:03

+0

迭代器是否从列表中删除元素并减小其大小? – Tariq 2015-02-17 16:11:27

+0

@Tariq:迭代器_iterates_。 – 2016-08-02 00:55:38

16

要体现在C++中新增和@karthik,用auto符延长有些过时的解决方案starting from C++11 it can be done shorter

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

even easier使用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 << " "; 
}