[英]What does the C++ standard say about std::vector<int> v1,v2; std::distance(v1.begin(),v2.begin())?
I have this code 我有这个代码
#include <vector>
#include <iostream>
int main(int argc, char* argv[])
{
std::vector<int> v1,v2;
std::cout << std::distance(v1.begin(),v2.begin());
return 0;
}
and it has a bug because it is not meaningful to compare the iterators of two different vectors. 它有一个bug,因为比较两个不同向量的迭代器没有意义。
I had a look at N3376 at 24.4.4 Iterator operations at page 815: 我在第815页的24.4.4迭代器操作中查看了N3376 :
template<class InputIterator> typename iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator last);
Requires : If
InputIterator
meets the requirements of random access iterator,last
shall be reachable fromfirst
orfirst
shall be reachable fromlast
;要求 :如果
InputIterator
满足随机访问迭代器的要求,则last
可以从first
或first
到达,从last
可以到达; otherwise,last
shall be reachable fromfirst
.否则,
last
应从到达first
。
Now I think that Requires is not fulfilled. 现在我认为需求没有实现。
What does the standard state should happen in this case? 在这种情况下,标准状态应该发生什么?
[iterator.requirements.general]: [iterator.requirements.general]:
An iterator
j
is called reachable from an iteratori
if and only if there is a finite sequence of applications of the expression++i
that makesi == j
.迭代器
j
被称为可以从迭代器i
到达 ,当且仅当存在表达式++i
的有限序列的应用程序时才使i == j
。
The problem is that once you incremented v1.begin()
v1.size()-1
times, the next increment operation induces undefined behavior, so v2.begin()
cannot be reached from v1.begin()
. 问题是,一旦你递增
v1.begin()
v1.size()-1
次,下一个增量操作引起未定义行为,所以v2.begin()
不能从达到v1.begin()
The same argument makes v1.begin()
unreachable from v2.begin()
. 相同的参数使
v1.begin()
无法从v2.begin()
。
In case your question was "What happens if a condition in a Requires section is violated?", look at [res.on.required]: 如果您的问题是“如果违反了” 要求“部分中的条件会发生什么情况?”,请查看[res.on.required]:
Violation of the preconditions specified in a function's Requires: paragraph results in undefined behavior unless the function's Throws: paragraph specifies throwing an exception when the precondition is violated.
违反函数的Requires:段中指定的前提条件会导致未定义的行为,除非函数的Throws: paragraph指定在违反前提条件时抛出异常。
In some implementations of std::distance
, the first iterator is incremented until it reaches the second iterator. 在
std::distance
一些实现中,第一个迭代器递增直到它到达第二个迭代器。 The iterations are counted: 计算迭代次数:
unsigned int counts = 0;
while (iter1 != iter2)
{
++counts;
++iter1;
}
If the iterators point to containers in different address spaces, the loop many not terminate. 如果迭代器指向不同地址空间中的容器,那么循环很多都不会终止。 Using the terms in the standard, the second iterator is not reachable .
使用标准中的术语,无法访问第二个迭代器。
不满足requires
,这意味着代码具有未定义的行为:任何事情都可能发生。
In this case will be undefined behavior. 在这种情况下将是未定义的行为。 Because
last
is not reachable from first
by (possibly repeatedly) incrementing first
. 因为
last
是不可达的距离first
的(可能重复)递增first
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.