如果第二个向量为空,为什么 std::equal 会崩溃

Why std::equal crashes if second vector empty

我正在使用 <algorithm> 中定义的 std::equals 来检查两个向量是否相等。当第二个向量为空时它会崩溃。我可以通过检查第二个向量是否为空来避免崩溃,但是是否有理由不包含 equal 函数本身的检查?

示例代码:

std::vector<int> a;
for (int i = 0; i < 3; ++i) a.emplace_back(i);

std::vector<int> b;
for (int i = 0; i < 0; ++i) b.emplace_back(i);

std::equal(a.begin(), a.end(), b.begin());

本次调用比较元素的范围(以比较次数为单位)

std::equal(a.begin(), a.end(), b.begin());

由前两个参数指定 [a.begin(), a.end() )。但是这个范围对于向量 b.

是无效的

使用这种形式的算法

template<class InputIterator1, class InputIterator2>
bool equal(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2);

其中两个比较容器的范围分别指定为

std::equal(a.begin(), a.end(), b.begin(), b.end());

你用 3 个参数调用 std::equal,在 https://en.cppreference.com/w/cpp/algorithm/equal 中说:

Returns true if the range [first1, last1) is equal to the range [first2, first2 + (last1 - first1)), and false otherwise

在你的案例中会导致未定义的行为

改为使用带有 4 个参数的 std::equal

std::equal(a.begin(), a.end(), b.begin(), b.end());

哪个会做:

Returns true if the range [first1, last1) is equal to the range [first2, last2), and false otherwise.

这就是你想要的。

或者,您可以只使用运算符 ==std::vector 重载一个:

a == b;