核心内容摘要
探索张柏芝警服照片大全高清:魅力与敬业的完美结合
STL 的const_iterator等价于 “指向常量的指针pointer-to-const”指向的值不可修改符合 “能加const就加” 的通用编程准则 —— 只要无需修改迭代器指向的值就应优先使用const_iterator但该迭代器的实用性随 C 版本迭代大幅提升C11 是关键转折点同时通用代码中需优先使用非成员函数版本的begin/end/cbegin等。
各 C 版本对 const_iterator 的支持差异
C98支持残缺实用性差const_iterator理论上符合规范但实际使用存在两大痛点创建麻烦非const容器无法直接获取const_iterator需强制类型转换或绑定到const引用才能得到使用受限insert/erase等容器操作仅接受iterator且const_iterator无法可移植转换为iterator即使reinterpret_cast也不行最终导致开发者被迫放弃使用违背 “能const则const” 的准则。
typedef std::vectorint::iterator IterT; typedef std::vectorint::const_iterator ConstIterT; std::vectorint values; … // 非const容器需强制转换才能获取const_iterator ConstIterT ci std::find(static_castConstIterT(values.begin()), static_castConstIterT(values.end()),
; // insert不接受const_iterator转换iterator也无可靠方法编译失败 values.insert(static_castIterT(ci),
;C11支持完善易用性大幅提升解决了 C98 的核心痛点让const_iterator真正实用容器新增cbegin/cend成员函数非const容器也能直接获取const_iteratorinsert/erase等操作支持接收const_iterator无需转换即可使用示例无需修改迭代器指向值的查找 插入场景可直接用cbegin/cend获取const_iterator代码简洁且符合规范。
std::vectorint values; … // 直接用cbegin/cend获取const_iteratorinsert原生支持 auto it std::find(values.cbegin(), values.cend(),
; values.insert(it,
;C11 的小缺陷与 C14 的补全C11 仅新增非成员函数begin/end缺失cbegin/cend/rbegin/rend等C14 补全了这些非成员函数满足 “最大程度通用的库代码” 需求适配原生数组、仅提供自由函数接口的第三方库等。
通用代码的适配方案C11 兼容若 C11 环境下 STL 未提供非成员cbegin等函数可自行实现兼容普通容器和原生数组核心逻辑通过const引用接收容器 / 数组调用 C11 提供的非成员begin—— 对const容器 / 数组begin会自动返回const_iterator数组场景下等价于指向const的指针无需依赖容器的cbegin成员函数适配性更强。
总结优先选用const_iterator而非iterator。
在最通用的代码中优先选用非成员函数版本的begin、end和rbegin等而非其成员函数版本。
原著在线阅读地址