一、迭代器(iterator)介紹
指針可以用來遍歷存儲空間連續的數據結構,但是對於存儲空間非連續的,就需要尋找一個行為類似指針的類,來對非數組的數據結構進行遍歷。因此,我們引入迭代器概念。
迭代器(Iterator)是一種檢查容器內元素並遍歷元素的數據類型。迭代器是指針的泛化,它允許程序員用相同的方式處理不同的數據結構(容器)。
1、頭文件
所有容器有含有其各自的迭代器型別(iterator types),所以當你使用一般的容器迭代器時,並不需要含入專門的頭文件。不過有幾種特別的迭代器,例如逆向迭代器,被定義於 <iterator> 中。
2 迭代器類型
迭代器共分為五種,分別為: 輸入迭代器(Input iterator)、輸出迭代器(Output iterator)、前向迭代器(Forward iterator)、雙向迭代器(Bidirectional iterator)、隨機存取迭代器(Random access iterator)。
二、容器迭代器的使用
下面列舉了些例子說明各個容器的用法:
1、vector
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
// Create and populate the vector
vector<int> vecTemp;
for (int i = 0; i<6; i++)
{
vecTemp.push_back(i);
}
// Display contents of vector
cout <<"Original deque: ";
vector<int>::iterator it;
for (it = vecTemp.begin(); it!=vecTemp.end(); it++)
{
cout <<*it <<" ";
}
return 0;
}
/*
輸出結果:
Original deque: 0 1 2 3 4 5
*/
2、deque
#include <iostream>
#include <deque>
using namespace std;
int main(int argc, char* argv[])
{
// Create and populate the deque
deque<int> dequeTemp;
for (int i = 0; i<6; i++)
{
dequeTemp.push_back(i);
}
// Display contents of deque
cout <<"Original deque: ";
deque<int>::iterator it;
for (it = dequeTemp.begin(); it != dequeTemp.end(); it++)
{
cout <<*it <<" ";
}
cout <<endl;
return 0;
}
/*
輸出結果:
Original deque: 0 1 2 3 4 5
*/
3、list
#include <iostream>
#include <list>
using namespace std;
int main(int argc, char* argv[])
{
// Create and populate the list
list<int> listTemp;
for (int i = 0; i<6; i++)
{
listTemp.push_back(i);
}
// Display contents of list
cout << "Original list: ";
list<int>::iterator it;
for (it = listTemp.begin(); it != listTemp.end(); it++)
{
cout << *it << " ";
}
cout << endl;
// Insert five 9 into the list
list<int>::iterator itStart = listTemp.begin();
listTemp.insert(itStart,5,9);
// Display the result
cout << "Result of list: ";
for (it = listTemp.begin(); it != listTemp.end(); it++)
{
cout << *it << " ";
}
cout << endl;
return 0;
}
/*
輸出結果:
Original list: 0 1 2 3 4 5
Result of list: 9 9 9 9 9 0 1 2 3 4 5
*/
4、set
#include <iostream>
#include <set>
using namespace std;
int main(int argc, char* argv[])
{
// Create and populate the set
set<char> setTemp;
for (int i = 0; i<6; i++)
{
setTemp.insert('F'-i);
}
// Display contents of set
cout <<"Original set: ";
set<char>::iterator it;
for (it = setTemp.begin(); it != setTemp.end(); it++)
{
cout <<*it <<" ";
}
cout <<endl;
return 0;
}
/*
輸出結果:
Original set: A B C D E F
*/
5、map
#include <iostream>
#include <map>
using namespace std;
typedef map<int, char> MyMap;
int main(int argc, char* argv[])
{
// Create and populate the map
MyMap mapTemp;
for (int i = 0; i<6; i++)
{
mapTemp[i] = ('F'-i);
}
// Display contents of map
cout <<"Original map: " <<endl;
MyMap::iterator it;
for (it = mapTemp.begin(); it != mapTemp.end(); it++)
{
cout << (*it).first << " --> ";
cout << (*it).second << std::endl;
}
cout <<endl;
return 0;
}
/*
輸出結果:
Original map:
0 --> F
1 --> E
2 --> D
3 --> C
4 --> B
5 --> A
*/