什么时候使用迭代器的"value_type"? [英] When is a `value_type` of an iterator used?

查看:120
本文介绍了什么时候使用迭代器的"value_type"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解何时实际使用iterator::value_type.

I am trying to understand when an iterator::value_type is actually used.

因为,所有迭代器运算符似乎仅使用iterator::pointeriterator::reference.

Because, all operators of iterators, seem to use only iterator::pointer and iterator::reference.

问题:iterator::value_type是否确实用于某物?

Question: Is iterator::value_type actually used for something?

其他问题:迭代器是否继承自

std::iterator<std::random_access_iterator_tag, int, std::ptrdiff_t, bool*, bool&>

引发一些语义问题?

编辑:要理解为什么我问这个问题,是因为我正在为类型为pointerreference是代理类的迭代器进行工作.

To understand why I am asking this question, it's because I am working on an iterator for a type for which pointer and reference are proxy classes.

推荐答案

我可以考虑在通用代码中使用它.假设您正在编写一个通用函数,该函数总结了C ++ 11中的范围.您可以将其写为

I can think of using it in generic code. Suppose you're writing a generic function that sums up a range in C++11. You can write it as

template<typename It>
auto sum(It begin, It end) -> typename It::value_type
{
    typename It::value_type _sum{}; 
    // compute the sum
    return _sum;
}

您当然可以使用decltype(*begin)代替,但是使用value_type看起来更整洁,更优雅.在C ++ 14中,我无法想到一个很好的用法,因为您可以在函数返回时具有自动类型推断.

Of course you can use decltype(*begin) instead, but using value_type looks neat-er and more elegant. In C++14 I cannot think of a really good use, since you can have auto type deduction on function return.

编辑正如@Luc Danton在评论中提到的那样,大多数时候使用decltype(*begin)会产生引用,因此您需要std::remove_reference,这看起来很讨厌.所以value_type派上用场了.

EDIT As mentioned by @Luc Danton in the comment, using decltype(*begin) yields a reference most of the time, so you'd need to std::remove_reference, which makes it look quite nasty. So value_type comes handy.

这篇关于什么时候使用迭代器的"value_type"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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