使用指针作为容器迭代器是否违反标准 [英] Does Using a Pointer as a Container Iterator Violate the Standard
问题描述
Angew发表了评论使用原始指针作为迭代器类型的vector
很好.那有点让我感到困惑.
Angew made a comment that a vector
using a raw pointer as it's iterator type was fine. That kinda threw me for a loop.
我开始研究它,发现对vector
迭代器的要求只是它们是,其中明确指出了指针符合条件:
I started researching it and found that the requirement for vector
iterators was only that they are "Random Access Iterators" for which it is explicitly stated that pointers qualify:
指向数组元素的指针满足所有要求
A pointer to an element of an array satisfies all requirements
是编译器甚至出于调试目的甚至向vector
提供迭代器的唯一原因,还是实际上我错过了vector
的要求?
Is the only reason that compilers even provide iterators to vector
for debugging purposes, or is there actually a requirement I missed on vector
?
推荐答案
§24.2.1
§ 24.2.1
由于迭代器是指针的抽象,因此其语义是大多数语义的概括 C ++中的指针集.这样可以确保每个带有迭代器的函数模板都可以正常工作 常规指针.
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
的所有要求.
So yes, using a pointer satisfies all of the requirements for a Random Access Iterator
.
std::vector
出于某些原因可能提供了迭代器
std::vector
likely provides iterators for a few reasons
-
标准要求.
The standard says it should.
如果像std::map
或std::set
这样的容器提供了迭代器,而std::vector
仅提供了value_type*
指针,那将很奇怪.迭代器在整个容器库中提供了一致性.
It would be odd if containers such as std::map
or std::set
provided iterators while std::vector
provided only a value_type*
pointer. Iterators provide consistency across the containers library.
它允许向量类型的特殊化,例如std::vector<bool>
,其中value_type*
指针将不是有效的迭代器.
It allows for specializations of the vector type eg, std::vector<bool>
where a value_type*
pointer would not be a valid iterator.
这篇关于使用指针作为容器迭代器是否违反标准的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!