近來,基本上所有現代編程語言都有一種對一個區間寫for循環的便捷方式。最終,C++也有了相同的概念;你可以給循環提供一個容器,它幫你迭代。
example:
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main() {
vector<int> num{3, 7, 1, 7, 9};
// 修改你正在迭代的容器的值,或者你想避免拷貝大的對象
for(auto &it : num) {
cout << ++it << endl;
}
// it 用於捕獲vector里面的值
for(auto it :num) {
cout << it << endl;
}
map<int, int> num_map;
num_map[2] = 4;
num_map[4] = 5;
num_map[6] = 1;
for(auto it : num_map) {
cout << it.first << endl
<< ",second: " << it.second << endl;
}
}
區間遍歷的意義:
Strings,arrays,和所有的STL容器可以被新的區間迭代方式迭代。但是如果你想讓你自己的數據結構使用這個新語法怎么辦?
為了使這個數據結構可迭代,它必須類似於STL迭代器。
這個數據結構必須要有begin和end方法,成員方法和獨立函數都行,這兩個方法分別返回開始和結束的迭代器
迭代器支持操作符、!=操作符、++方法(前綴形式,成員函數和獨立函數都行)
就這些!實現這五個函數,你就可以有一個支持區間迭代的數據結構。因為begin、end可以是非成員函數,你甚至可以適配現有數據結構而不用實現STL風格的迭代器。所有你要做的是創建你自己的支持、前綴++和!=的迭代器,並且定義好自己的begin、end。
另外,vector的幾種遍歷方式:
#include <vector>
#include <iostream>
#include <algorithm> // for_each
using namespace std;
struct Point
{
double x;
double y;
Point()
{
x = 0;
y = 0;
}
};
int main()
{
vector<Point> m_testPoint;
m_testPoint.clear();
m_testPoint.shrink_to_fit();
for (int i = 0; i<10; ++i)
{
Point temp;
temp.x = i*i;
temp.y = i*i;
m_testPoint.push_back(temp);
}
//第一種遍歷方式,下標
cout << "第一種遍歷方式,下標訪問" << endl;
for (int i = 0; i<m_testPoint.size(); ++i)
{
cout << m_testPoint[i].x << " " << m_testPoint[i].y << endl;
}
//第二種遍歷方式,迭代器
cout << "第二種遍歷方式,迭代器訪問" << endl;
for (vector<Point>::iterator iter = m_testPoint.begin(); iter != m_testPoint.end(); iter++)
{
cout << (*iter).x << " " << (*iter).y << endl;
}
//第三種遍歷方式,auto關鍵字
cout << "C++11,第三種遍歷方式,auto關鍵字" << endl;
for (auto iter = m_testPoint.begin(); iter != m_testPoint.end(); iter++)
{
cout << (*iter).x << " " << (*iter).y << endl;
}
//第四種遍歷方式,auto關鍵字的另一種方式
cout << "C++11,第四種遍歷方式,auto關鍵字" << endl;
for (auto i : m_testPoint)
{
cout << i.x << " " << i.y << endl;
}
// 第五種遍歷方式,for_each
cout << "C++11,第五種遍歷方式,for_each" << endl;
for_each(m_testPoint.cbegin(), m_testPoint.cend(),
[](const auto &val) -> void { cout << val.x << " " << val.y << endl; });
return 0;
}
參考