std :: vector< T> :: iterator可以只是T *吗? [英] Can std::vector<T>::iterator simply be T*?

查看:168
本文介绍了std :: vector< T> :: iterator可以只是T *吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的理论问题:一个简单的指针是 std :: vector 的有效迭代器类型吗?

Simple theoretical question: would a simple pointer be a valid iterator type for std::vector?

对于其他容器(例如list,map),这是不可能的,但对于 std :: vector 保证保持的数据是连续的,所以我看不出为什么不知道。

For other containers (e.g. list, map), that would not be possible, but for std::vector the held data is guaranteed to be contiguous, so I see no reason why not.

据我所知,某些实现(例如Visual Studio)会对调试版本进行一些安全检查。但这是在UB领域,所以对于明确定义的行为,我认为没有区别。

As far as I know, some implementations (e.g. Visual Studio) do some safe checks on debug build. But that is in UB territory, so for well defined behavior I think there is no difference.

除了一些检查(修改未定义的行为),是否有任何优势使用类而不是简单的指针用于向量迭代器?

Apart for some checks ("modifying" undefined behavior), are there any advantages of using a class instead of a simple pointer for vector iterators?

推荐答案


一个简单的指针是 std :: vector 的有效迭代器类型?

是。还有 std :: basic_string std :: array


使用类而不是向量迭代器的简单指针有什么好处吗?

are there any advantages of using a class instead of a simple pointer for vector iterators?

它提供了一些额外的类型安全性,因此如下所示的逻辑错误无法编译:

It offers some additional type safety, so that logic errors like the following don't compile:

std::vector<int> v;
int i=0;
int* p = &i;
v.insert(p, 1); // oops, not an iterator!
delete v.begin();  // oops!

std::string s;
std::vector<char> v;
// compiles if string and vector both use pointers for iterators:
v.insert(s.begin(), '?');
std::array<char, 2> a;
// compiles if array and vector both use pointers for iterators:
v.erase(a.begin());

这篇关于std :: vector&lt; T&gt; :: iterator可以只是T *吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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