近来,基本上所有现代编程语言都有一种对一个区间写for循环的便捷方式。最终,C++也有了相同的概念;你可以给循环提供一个容器,它帮你迭代。
example:
#include
#include
#include
using namespace std;
int main() {
vector
// 修改你正在迭代的容器的值,或者你想避免拷贝大的对象
for(auto &it : num) {
cout << ++it << endl;
}
// it 用于捕获vector里面的值
for(auto it :num) {
cout << it << endl;
}
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
#include
#include
using namespace std;
struct Point
{
double x;
double y;
Point()
{
x = 0;
y = 0;
}
};
int main()
{
vector
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 { cout << m_testPoint[i].x << " " << m_testPoint[i].y << endl; } //第二种遍历方式,迭代器 cout << "第二种遍历方式,迭代器访问" << endl; for (vector { 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; } 参考 C++11系列-区间迭代 C++ Vector遍历的几种方式 论C++11 中vector的N种遍历方法