gpt4 book ai didi

C++ std::set::erase 与 std::remove_if

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:52:00 24 4
gpt4 key购买 nike

此代码有 Visual Studio error C3892。如果我将 std::set 更改为 std::vector - 它有效。

std::set<int> a;
a.erase(std::remove_if(a.begin(), a.end(), [](int item)
{
return item == 10;
}), a.end());

怎么了?为什么我不能将 std::remove_ifstd::set 一起使用?

最佳答案

您不能使用 std::remove_if()具有 const 的序列部分。 std::set<T>的序列元素由 T const 组成对象。事实上,我们昨天在标准 C++ 委员会讨论了这个问题,并且有一些支持创建专门处理 erase() 的算法。从容器中提取对象。它看起来像这样(另见 N4009 ):

template <class T, class Comp, class Alloc, class Predicate>
void discard_if(std::set<T, Comp, Alloc>& c, Predicate pred) {
for (auto it{c.begin()}, end{c.end()}; it != end; ) {
if (pred(*it)) {
it = c.erase(it);
}
else {
++it;
}
}
}

(它实际上可能会委托(delegate)给一个算法调度到上面的逻辑,因为相同的逻辑对于其他基于节点的容器是相同的)。

对于你的特定用途,你可以使用

a.erase(10);

但这仅适用于当上述算法适用于任意谓词时要删除 key 的情况。另一方面,a.erase(10)可以利用std::set<int>的结构,将是 O(log N),而算法是 O(N)(使用 N == s.size() )。

关于C++ std::set::erase 与 std::remove_if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24263259/

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