Angew made a comment vector
使用原始指针作为迭代器类型很好。这让我大吃一惊。
我开始研究它,发现对 vector
迭代器的要求只是它们是 "Random Access Iterators"明确指出指针符合条件:
A pointer to an element of an array satisfies all requirements
编译器甚至为 vector
提供迭代器以进行调试的唯一原因,还是实际上我错过了 vector
的要求?
最佳答案
§ 24.2.1
Since iterators are an abstraction of pointers, their semantics is a generalization of most of the semantics of pointers in C++. This ensures that every function template that takes iterators works as well with regular pointers.
所以是的,使用指针满足 Random Access Iterator
的所有要求.
std::vector
可能出于某些原因提供迭代器
标准说应该。
如果像
std::map
这样的容器会很奇怪或std::set
std::vector
时提供迭代器只提供一个value_type*
指针。迭代器提供跨容器库的一致性。它允许 vector 类型的特殊化,例如
std::vector<bool>
其中一个value_type*
指针不是有效的迭代器。
关于c++ - 使用指针作为容器迭代器是否违反标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41853089/