gpt4 book ai didi

c++ - C++ 标准对 std::vector v1,v2; 有什么看法?标准::距离(v1.begin(),v2.begin())?

转载 作者:IT老高 更新时间:2023-10-28 12:50:46 27 4
gpt4 key购买 nike

我有这个代码

#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;
}

它有一个错误,因为比较两个不同 vector 的迭代器没有意义。

我看过 N337624.4.4 迭代器操作 在第 815 页:

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 from first or first shall be reachable from last; otherwise, last shall be reachable from first.

现在我认为 Requires 没有满足。

在这种情况下,标准状态应该是什么?

最佳答案

[iterator.requirements.general]:

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.

问题是,一旦你增加了 v1.begin() v1.size()-1 次,下一次递增操作会引发未定义的行为,所以 无法从 v1.begin() 访问 v2.begin()。相同的论点使 v1.begin() 无法从 v2.begin() 访问。


如果您的问题是“如果违反 Requires 部分中的条件会发生什么?”,请查看 [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.

关于c++ - C++ 标准对 std::vector<int> v1,v2; 有什么看法?标准::距离(v1.begin(),v2.begin())?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29654728/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com