深入理解迭代器:概念、分类与应用
1. 迭代器基础
迭代器为识别 STL 及其他地方的元素范围提供了标准机制。元素范围的指定独立于元素的来源,只要迭代器满足算法的要求,给定的算法就可以应用于任何来源的元素范围。
1.1 获取迭代器
可以通过调用容器对象的 begin() 和 end() 成员函数来获取迭代器,它们分别返回指向第一个元素和最后一个元素之后位置的迭代器。 end() 返回的迭代器不指向有效元素,因此不能对其进行解引用或递增操作。
#include <numeric>
#include <iostream>
#include <iterator>
int main()
{
double data[] {2.5, 4.5, 6.5, 5.5, 8.5};
std::cout << "The array contains:\n";
for (auto iter = std::begin(data); iter != std::end(data); ++iter)
std::cout << *iter << " ";
auto total = std::accumulate(std::begin(data), std::end(data), 0.0);
std::cout << "\nThe sum of the array elements is " <<
超级会员免费看
订阅专栏 解锁全文

被折叠的 条评论
为什么被折叠?



