gpt4 book ai didi

c++ - 排序时更改排序顺序是未定义的行为吗?

转载 作者:太空狗 更新时间:2023-10-29 20:37:15 27 4
gpt4 key购买 nike

想象一下以下场景:

std::atomic<int>  values[10];
std::size_t indices[10];

void sort() {
std::iota(indices, indices+10, 0);

std::sort(indices, indices+10,
[&](size_t lhs, size_t rhs) { return values[lhs] < values[rhs]; });
}

在运行 sort() 时,另一个线程正在更改 values。这只会导致索引在之后无法正确排序,还是实际上是未定义的行为?

最佳答案

可能(见下文)这是未定义的行为;在实践中,我已经看到了普通的崩溃(对于容器边界外的访问),甚至只是因为不正确的(=不引起总排序)比较器,和<在排序时更改索引肯定无法导致总排序

有趣的是,该标准并未明确提及与此问题相关的未定义行为; C++11 §5.4 ¶3 只是指出

For algorithms other than those described in 25.4.3 to work correctly, comp has to induce a strict weak ordering on the values.

而且我没能在周围看到“正确工作”的正式定义;在整个第 25 章(描述 <algorithm> )中,甚至连“未定义”这个词都没有被提及。

关于c++ - 排序时更改排序顺序是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35502809/

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