有没有办法使用独立的`std :: begin`和const_iterator?

时间:2013-11-08 18:30:19

标签: c++ c++11 iterator const-correctness

我喜欢一致性。我最近提出了使用std::begin与... std::vector<int>::begin,一致的决定似乎是使用前者,因为它更为笼统。但我想我在泥里找到了一根棍子。有时,您希望传达在循环播放时不会更改容器,因此调用std::vector<int>::cbegin。如果您有时iter = v.cbegin()而其他时间iter = begin(v),则会使您的代码非常不对称。有没有办法解决这种缺乏对称性的问题,你是否仍然建议std::begin给出这种知识?为什么C ++没有std::cbegin

2 个答案:

答案 0 :(得分:40)

C ++ 14有cbegin / cend /等。它开始在主要编译器中可用。

答案 1 :(得分:3)

例如,当您的容器被声明为“const”时,它将被传递给foo(const std::vector<int> & v)的函数,然后std::begin将实际返回const_iterator