使用指针作为容器迭代器是否违反标准 [英] Does Using a Pointer as a Container Iterator Violate the Standard

查看:96
本文介绍了使用指针作为容器迭代器是否违反标准的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  1. 标准要求.

  1. The standard says it should.

如果像std::mapstd::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屋!

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