gpt4 book ai didi

c++ - 在 C++11 中从 C++17 重新实现 std::map::try_emplace()?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:35:22 26 4
gpt4 key购买 nike

std::map::try_emplace()看起来非常方便和高效,但它仅在 C++17 中可用。是否可以在 C++11 中重新实现它?

template <class... Args>
pair<iterator, bool> try_emplace(const key_type& k, Args&&... args);

最佳答案

对于有序映射,您可以使用 lower_bound 接近行为:

template <class M, class... Args>
std::pair<typename M::iterator, bool>
try_emplace_m(M& m, const typename M::key_type& k, Args&&... args) {
auto it = m.lower_bound(k);
if (it == m.end() || m.key_comp()(k, it->first)) {
return {m.emplace_hint(
it, std::piecewise_construct,
std::forward_as_tuple(k),
std::forward_as_tuple(std::forward<Args>(args)...)), true};
}
return {it, false};
}

对于无序 map ,您不能使用lower_bound。您可以将其替换为 find,并将测试替换为 key_eq(),以获得功能版本,不过在插入的情况下会执行重复查找。 Sp 纯粹就算法复杂性而言,这个新成员函数在无序情况下具有更大的权重,用户目前无法仅使用公共(public) API 来实现。但增加的便利同样适用于这两种情况。

关于c++ - 在 C++11 中从 C++17 重新实现 std::map::try_emplace()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34382073/

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