STL中迭代器的类型是什么? [英] what is the type of an iterator in STL?

查看:29
本文介绍了STL中迭代器的类型是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c++ 中的每个变量都有一些类型,比如 int ii 有一个类型 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 as we 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++ 程序以统一的方式处理不同的数据结构(容器).为了能够构建在不同类型的数据结构上正确有效地工作的模板算法,该库不仅规范了接口,还规范了迭代器的语义和复杂性假设.

Iterators are a generalization of pointers that allow a C++ program to work with different data structures (containers) in a uniform manner. To be able to construct template algorithms that work correctly and efficiently on different types of data structures, the library formalizes not just the interfaces but also the semantics and complexity assumptions of iterators.

短语指针的泛化"意味着指针迭代器.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中迭代器的类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆