实时 C++ 教程:高级特性与应用
1. 迭代器与常量迭代器
在 C++ 中,迭代器是一种强大的工具,用于遍历容器中的元素。常量迭代器则提供了只读访问的能力。以下是一些示例代码:
const_iterator_type const_iterator1 = cnt.begin();
const_iterator_type const_iterator2 = cnt.cbegin();
// 可通过非常量迭代器写入
*(nonconst_iterator) = 5;
// 可通过常量迭代器读取
const int n1 = *const_iterator1;
const int n2 = *const_iterator2;
// 不能通过常量迭代器写入
*(const_iterator1) = 5;
*(const_iterator2) = 5;
cbegin()
中的 “c” 强调了迭代器以常量方式遍历容器元素,类似于 const_iterator
。一些特殊的容器成员迭代器函数,如 begin()
和 end()
有常量和非常量版本,而 cbegin()
和 cend()
则仅为常量版本。标准迭代器类定义在 <iterator>
中。
2. STL 算法
STL 拥有大量的模板算法,专门用于以通用方式操作迭代器范围。大多数标准算法定