gpt4 book ai didi

c++ - 与 if 进行比较时与与存储值进行比较时的 std::vector删除结果不同

转载 作者:行者123 更新时间:2023-12-03 07:51:20 28 4
gpt4 key购买 nike

出于某种原因,在比较 if 语句内的 vector::erase 返回值时,或者如果我先存储值然后进行比较,我会得到不同的结果。但这似乎只发生在 g++ 中。

这是使用 g++、libstdc++ 和 -std=c++14 标志在 Ubuntu 20.04 AMD64 上构建的。g++ -std=c++14 foo.cpp && ./a.out

这将返回false

#include <vector>
#include <iostream>
#include <algorithm>

int main()
{
std::vector<int> v{0, 1, 8, 3, 8, 5, 8, 7,8, 9};
int thing_id{9};

std::vector<int>::iterator const cit{
std::remove_if(v.begin(),
v.end(),
[thing_id](int const& thing) -> bool {
return thing == thing_id;
})};

if (v.erase(cit, v.cend()) == v.cend()) {
std::cout << "true\n";
return true;
}
else {
std::cout << "false\n";
return false;
}
}

这将返回true

#include <vector>
#include <iostream>
#include <algorithm>

int main()
{
std::vector<int> v{0, 1, 8, 3, 8, 5, 8, 7,8, 9};
int thing_id{9};

std::vector<int>::iterator const cit{
std::remove_if(v.begin(),
v.end(),
[thing_id](int const& thing) -> bool {
return thing == thing_id;
})};

auto const prev_end = v.erase(cit, v.cend());
if (prev_end == v.cend()) {
std::cout << "true\n";
return true;
}
else {
std::cout << "false\n";
return false;
}
}

使用 QCC 和 libc++ 构建 QNX ARM64 时,两个代码段都将返回 true

这是为什么呢?比较不应该是确定性的吗?有人可以向我解释一下这是怎么回事吗?

最佳答案

何时 std::vector::erase 成功后,它会使删除点或删除点之后的元素的迭代器(和引用)无效。因此end()迭代器也会失效。也就是说,删除成功后, vector 就会有新的cend() .

这很重要,因为比较运算符的计算顺序未指定,请参阅 this answer 。换句话说,给定表达式 v.erase(cit, v.cend()) == v.cend() ,编译器可以自由决定评估最右边的 v.cend()首先,记住它,然后才评估 v.erase(cit, v.cend()) 的返回值。在这种情况下,它将把新返回的尾后迭代器值与旧的 v.cend() 进行比较。值(即,在它因删除而失效之前)。

关于c++ - 与 if 进行比较时与与存储值进行比较时的 std::vector删除结果不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77081556/

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