我编写了一个函数,它需要向量上的一对 RandomAccessIterators 来对其进行排序。这很好用。我编写了一个表现出奇怪行为的测试用例。
我的功能的“模拟”:
#include <vector>
#include <iostream>
#include <cassert>
int main(){
std::vector<int> testing = std::vector<int>(0);
assert(testing.begin() <= (testing.end()-1)); //why no fail?
std::cout << (testing.begin() <= (testing.end())); //prints 1
std::cout << (testing.begin() <= (testing.end()-1)); //prints 1 unexpectedly
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当向量testing为空时,我希望函数不执行任何操作或抛出异常。我不知道哪一个更好。欢迎提出建议。
我已阅读有关迭代器的 C++ 文档,并且知道当测试为空时(testing.begin() <= testing.end()) 进行评估,因为空向量的开始和结束是相同的。True
为什么testing.end()-1的计算结果不小于testing.begin()?我该怎么做才能获得所需的行为,即异常或立即返回?