问题描述
c++ 中的每个变量都有一些类型,比如 int i
,i
有一个类型 int
.类似地,我们在 STL 中有迭代器,我们声明它像这样
Every Variable in c++ has some type like in int i
, i
has a type int
.Similarly we have iterators in STL which we declare say something like this
map<string,int>::iterator it .
这里的 it
是什么类型的?它是指针类型还是指针类型在存储 int 或其他类型的向量的情况下,我们通常遵循迭代器来获取这些迭代器关联或指向的值.或者运算符 *
为 STL 中的迭代器重载了?
What is the type of the it
over here ? Is it pointer type or is it a pointer type aswe gerally deference iterators to fetch values associated or pointed by those itearors in case of vectors which store int or some other type.? Or the operator *
is overloaded for iterators in STL ?
推荐答案
24.2.1/1 [iterator.requirements.general] 总结得很好:
24.2.1/1 [iterator.requirements.general] sums it up nicely:
迭代器是指针的泛化,它允许 C++ 程序以统一的方式处理不同的数据结构(容器).为了能够构建在不同类型的数据结构上正确有效地工作的模板算法,该库不仅规范了接口,还规范了迭代器的语义和复杂性假设.
短语指针的泛化"意味着指针是迭代器.std::vector::iterator
可以是 typedef T *
.然而,大多数迭代器通过操作符重载来实现接口.(请注意,迭代器也不需要属于容器.)
The phrase "generalization of pointers" means that pointers are iterators. std::vector<T>::iterator
is allowed to be a typedef T *
. However, most iterators achieve the interface by operator overloading. (Note that iterators don't need to belong to containers, either.)
这种语言非常典型地代表了 C++ 标准的编写方式.它描述了事物的行为方式,但避免根据基类定义接口.有多种迭代器:输入、输出、前向、双向和随机访问.每个都有不同的规范,虽然随机访问是双向接口的严格超集,但它们在 C++ 类型系统中完全无关.
Such language is very typical of the way the C++ standard is written. It describes how things behave, but avoids defining interfaces in terms of base classes. There are various kinds of iterators: input, output, forward, bidirectional, and random-access. Each has a different specification, and although random-access is a strict superset of the bidirectional interface, they are totally unrelated in the C++ type system.
迭代器可以是任何重载了 ++
和 *
的类,并且是 std::iterator_traits
的有效特化.有一个基类std::iterator
,它与std::iterator_traits
一起工作来定义必要的接口.这是 C++ 泛型编程和特征类的一个很好的案例研究.
An iterator can be any class with ++
and *
overloaded, and a valid specialization of std::iterator_traits
. There is a base class std::iterator
which works with std::iterator_traits
to define the necessary interface. It is a good case study in C++ generic programming and traits classes.
这篇关于STL中迭代器的类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!