非成员的begin()、end()可以应用在数组中,使得对数组的处理可以像其他STL容器一样。
#include <iostream>
#include <algorithm>
int main()
{
int datas[] = { 1, 2, 3, 4, 5 };
// 原来便利数组方式,通过sizeof(datas)/sizeof(datas[0])获得数组大小
for (int idx = 0; idx < (sizeof(datas) / sizeof(datas[0])); ++idx)
{
std::cout << datas[idx] << std::endl;
}
// std::begin(datas)获取迭代器指向数组首地址 std::end(datas)获取迭代器指向数组最后一个元素的下一位置
for (auto iter = std::begin(datas); iter != std::end(datas); ++iter)
{
std::cout << *iter << std::endl;
}
// 查找数组中的元素
auto iter = std::find(std::begin(datas), std::end(datas), 2);
if (iter != std::end(datas))
{
std::cout << "Find 2" << std::endl;
}
else
{
std::cout << "Not Find 2" << std::endl;
}
return 0;
}