是否定义为C ++标准算法提供一个反向范围? [英] Is it defined to provide an inverted range to C++ standard algorithms?

查看:183
本文介绍了是否定义为C ++标准算法提供一个反向范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑标准算法,例如 std :: for_each

template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f);

据我所知,实际上没有对< <$ c $> InputIterator 参数的状态。

As far as I can tell, there is actually no requirement placed on the relative states of the two InputIterator arguments.

这是否意味着以下是技术上有效的?还是未定义?

Does that mean that the following is technically valid? Or is it undefined? What can I realistically expect it to do?

std::vector<int> v{0,1,2,3,4};
std::for_each(
   v.begin()+3,  // range [3,0)
   v.begin(),
   [](int){}
);

geordi 告诉我:


错误:function需要一个有效的迭代器范围[__first,__last] 。 [+ 13 lost lines]

error: function requires a valid iterator range [__first, __last). [+ 13 discarded lines]

但我不知道这个调试诊断符合的程度。

but I can't tell how compliant this debug diagnostic is.

我试图 确定如何定义下列行为的显式性时,我想出了这个问题:

I came up with this question when trying to pedantically determine how explicit is defined the behaviour of the following:

std::vector<int> v; // <-- empty
std::for_each(      // <-- total no-op? stated or just left to implication?
   v.begin(),
   v.end(),
   [](int){}
);


推荐答案

标准明确要求最后迭代器到第一迭代器可达。这意味着通过递增第一应该能够最终命中 last

The standard explicitly requires the last iterator to be reachable from the first iterator. That means that by incrementing first one should be able to eventually hit last.


24.1迭代器要求

...

6 迭代器 j 被称为可从迭代器获得 i 如果且仅当
存在表达式 ++ i 的有限序列应用程序
使得 i == j 。如果 j 可从 i 到达,它们引用相同的
容器。

6 An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j. If j is reachable from i, they refer to the same container.

7 大多数库的操作
的数据结构的算法模板都有使用范围的接口。范围是指定计算开始和结束的迭代器对

范围 [i,i)是一个空范围;一般来说,范围 [i,j)是指
数据结构中以
<$ c $指向的元素开始的元素c> i ,但不包括 j 指向的那个。范围 [i,j)
有效,当且仅当 j 可从 i
应用程序的函数在库中的无效范围的结果是
未定义。

7 Most of the library’s algorithmic templates that operate on data structures have interfaces that use ranges. A range is a pair of iterators that designate the beginning and end of the computation. A range [i, i) is an empty range; in general, a range [i, j) refers to the elements in the data structure starting with the one pointed to by i and up to but not including the one pointed to by j. Range [i, j) is valid if and only if j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined.

这篇关于是否定义为C ++标准算法提供一个反向范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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