c++ - 为什么迭代器类型与 vector 容器中的 value_type * 不匹配?

标签 c++ vector stl

根据最新的STL源码,我可以在STL_vector.h中找到如下内容

template <class _Tp, class _Alloc = __STL_DEFAULT_ALLOCATOR(_Tp) >
class vector : protected _Vector_base<_Tp, _Alloc>   
{
private:
  typedef _Vector_base<_Tp, _Alloc> _Base;
public:
  typedef _Tp value_type;
  typedef value_type* pointer;
  typedef const value_type* const_pointer;
  typedef value_type* iterator;
  typedef const value_type* const_iterator;
  typedef value_type& reference;
  typedef const value_type& const_reference;
  typedef size_t size_type;
  typedef ptrdiff_t difference_type;
...

int main() {
vector<string>::iterator it;

cout << "iterator type check 1 " << (typeid(it) == typeid(string *)) << endl;
cout << "iterator type check 2" << (typeid(vector<string>::iterator) == typeid(vector<string>::value_type *)) << endl;
cout << "iterator type check 3" << (typeid(vector<string>::pointer) == typeid(vector<string>::value_type *)) << endl;
cout << "iterator type check 4" << (typeid(string *) == typeid(vector<string>::value_type *)) << endl;

但是,当我使用 clang++ 编译上面的 main 时,我得到了 iterator 和 value_type * 的不匹配结果。 结果是 1/2 不匹配,3/4 匹配。但是,我预计 1/2 也应该匹配。 这是因为我指的是最新的 STL 代码吗?

最佳答案

STL 不是 C++ 标准库。 C++ 标准允许实现将指针用于随机访问迭代器,但不强制执行。 clang 和 gcc 都为这些迭代器使用用户定义的类型,而不是指针。 GCC 也不是。

您需要查看您实际尝试编译的代码的实现。那不是 STL。

例如,在 gcc 4.8 上 std::vector::iterator

typedef __gnu_cxx::__normal_iterator<pointer, vector> iterator;

其中 __normal_iterator 是一个类模板。

关于c++ - 为什么迭代器类型与 vector 容器中的 value_type * 不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22140101/

相关文章:

python - OpenCV 数字合并到周围的盒子中

c++ - vector 的下标有时超出范围

c++ - next_permutation 问题 c++

c++ - 程序在 Visual Studio 2010 上编译但不在 VS 2015 上编译

c++ - 为什么同一编译器的不同版本会给出不同的结果?

c++ - 如何通过SAT和优化解决顶点覆盖问题?

c++ - 无法将字段 <Object name> 声明为抽象类型

C++ vector 排序简单地说

c++ - 将关键点转换为 mat 或将它们保存到文本文件 opencv

c++ - 使用 std::future 无效使用不完整类型