const_iterator和const_iterator :: value_type的常量性 [英] const_iterator and constness of const_iterator::value_type

查看:90
本文介绍了const_iterator和const_iterator :: value_type的常量性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要使用STL

std::iterator_traits<const T*>::value_type

std::iterator_traits<T*>::value_type

为什么这样设计?第一个不应该是 const T 而第二个是 T 吗?您应该如何采用迭代器的基本const正确类型?我知道您可以编写自己的模板类和专业化知识并从中获取

Why it is designed like that? Shouldn't the first be const T and the second only T? How are you supposed to take the underlying const correct type of an iterator? I know you can write your own template class and specialization and get it from

    std::iterator_traits<const T*>::pointer

但是不应该有一个持有它的成员typedef吗?

but shouldn't there be a member typedef that holds it?

推荐答案

它允许我执行以下操作:

It allows me to do this:

std::iterator_traits<I>::value_type val = *iter;
val += 5;
doSomething(val);

但是如果value_type是const则比较困难,因为我需要使用remove_const.

But that's harder if value_type is const, because I need to use remove_const.

如果我不想获取可修改的值,那么value_type是否为const都没关系:

If I don't want to get a modifiable value then it doesn't matter whether value_type is const or not:

const std::iterator_traits<I>::value_type cval = *iter;
std::iterator_traits<I>::reference        ref  = *iter;

这两种方法都适用于const迭代器和非const迭代器,并且无论value_type是否为const都可以使用,但是第一个示例仅在其value_type为非const的情况下才适用于const迭代器.

Both of these work for const iterators and non-const iterators, and both work whether value_type is const or not, but the first example only works for const iterators if their value_type is non-const.

您应该如何采用迭代器的基本const正确类型?

How are you supposed to take the underlying const correct type of an iterator?

迭代器不一定具有自己的基础类型,迭代器通常引用某个范围或某个集合,而该集合就是具有基础类型的东西.例如std::list<int>::const_iteratorvalue_typestd::list<int>::value_type,而不是const int.

An iterator doesn't necessarily have an underlying type of its own, an iterator usually refers to some range or some collection, and that collection is what has an underlying type. e.g std::list<int>::const_iterator's value_type is std::list<int>::value_type, which is int not const int.

您不一定非要知道底层类型是什么,更可能想知道*iter的结果是什么,而这正是iterator_traits<I>::reference告诉您的.

You don't necessarily want to know what the underlying type is anyway, it's more likely you want to know what the result of *iter is, and that's what iterator_traits<I>::reference tells you.

这篇关于const_iterator和const_iterator :: value_type的常量性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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