迭代器是C++中非常重要的一种结构,它为遍历不同烈性容器中的元素提供了一种一致的方法。标准模板库(STL )就是采用迭代器访问容器中的元素。
为了从一个链表获取迭代器,我们要修改一下LinkedList类,增加两个函数:
Iterator<T> begin();
Iterator<T> end();
LinkedList类中定义了函数begin()和end()。一个LinkedList对象可以调用begin()和end()来得到一个指向列表头元素或尾元素之后的Iterator对象。注意,end()返回的是列表表尾之后的位置,此迭代器的current指针实际上为NULL.
TestIterator.cpp
#include <iostream>
#include <string>
#include "NewlInkedList.h"
using namespace std;
int main(){
// Create a list for strings
LinkedList<string> list;
// Add elements to the list
list.add("America");
list.add("Canada");
list.add("Russia");
list.add("France");
// Traverse a list using iterators
for(Iterator<string> iterator = list.begin(); iterator != list.end(); iterator++){
cout << *iterator <<" ";
}
return 0;
}