如何使用 RandomAccessIterator 检查 std::vector 是否为空?

问题描述 投票:0回答:1

我编写了一个函数,它在向量上使用一对 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;
}

当向量

testing
为空时,我希望函数不执行任何操作OR抛出异常。我不知道哪一个更好。感谢建议。

我已阅读有关迭代器的 C++ 文档,并且知道当测试为空时,

(testing.begin() <= testing.end())
会计算
True
,因为空向量的 begin 和 end 是相同的。

为什么testing.end()-1的计算结果不小于testing.begin()?我该怎么做才能获得所需的行为,即异常或立即返回?

c++ iterator std
1个回答
0
投票

我已阅读有关迭代器的 C++ 文档,并且知道 (testing.begin() <= testing.end()) evaluates True when the testing is empty, as begin and end are the same for empty vectors.

确实如此。

testing.begin() == testing.end()
当向量为空时。

为什么testing.end()-1的计算结果不小于testing.begin()?

因为迭代器不是整数。递减迭代器使其引用容器中的前一个元素。

begin
之前没有元素。当
end
等于
begin
时,则
end
之前也没有元素。您无法使
end
迭代器引用空容器中的前一个元素,因为不存在这样的元素。当
testing.end() -1
为空时,
testing
未定义。

我该怎么做才能获得所需的行为,即异常或立即返回?

如果你想检查向量是否为空,你可以检查是否为

testing.begin() == testing.end()
或使用其
empty()
方法。未定义的行为不会引发异常或导致立即返回,它是未定义的。

© www.soinside.com 2019 - 2024. All rights reserved.