gcc支持cbegin和cend方法

时间:2012-02-19 22:36:54

标签: c++ gcc

哪个版本的gcc编译器支持容器的免费const_iterator方法,例如:cbegincendcrbegincrend。我使用gcc 4.6.1和-std=c++0x标志启用的c ++ 0x功能,但这些方法无法在我的代码中解析。

4 个答案:

答案 0 :(得分:4)

不幸的是,标准中没有自由函数cbegin / cend,也没有任何反向版本。但是,您始终可以使用强制转换来获取常量迭代器:

auto it = std::begin(static_cast<T const &>(x));

使用std::add_const中的<type_traits>,如果你需要这么多,你甚至应该能够掌握相当普遍的东西。


容器成员函数cbegin / crbegin等都是C ++ 11的一部分,GCC已经支持了一段时间;很可能自4.3(当C ++ 11支持首次开始时)。 GCC 4.6肯定支持那些;如果您遇到麻烦,请发布麻烦的代码。

答案 1 :(得分:1)

我的实验表明默认情况下“cbegin”不可用(来自<vector> <map>个STL容器)。除非您指定--std=c++0x--std=c++11

以下是我对GCC 4.8的解释:

http://ascii.io/a/4539

如果您的编译器不支持那些--std开关(就像我在某些跨平台工具链上所做的那样),您可能只使用以下内容:

for (std::vector<string>::const_iterator it = vec.begin(), ite = vec.end();
                                         it != ite; ++it) {
    /* ... ... */
}

这适用于不支持C ++ 11的“自动”关键字功能的GCC版本。

答案 2 :(得分:0)

适合我(GCC 4.6.0):

#include <vector>

int main() {
  std::vector<int> vec;
  auto it = vec.cbegin();
  // int& val = *it;  // gives compiler error, as expected
}

成员函数也出现在stl_vector.h

答案 3 :(得分:0)

你可以添加自己的吗?

template< class C > 
auto cbegin( C& c ) -> decltype(c.cbegin());

template< class C > 
auto cbegin( const C& c ) -> decltype(c.cbegin())
相关问题