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

Re-implementing std::map::try_emplace() from C++17 in C++11?

本文关键字:std try emplace map 中从 C++11 C++17 新实现 实现      更新时间:2023-10-16

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};
}

对于无序映射,不能使用lower_bound。您可以用find替换它,用key_eq()替换测试,以获得一个功能版本,但在插入的情况下,它将执行重复查找。Sp纯粹就算法复杂性而言,这个新的成员函数在无序的情况下发挥了更大的作用,而用户目前只能使用公共的API来实现这种情况。但增加的便利性同样适用于这两种情况。

嗯。。。只需搜索之前的值?

auto it = map.find(k);
if (it == map.end()){ //value does not exist
    auto newIt = map.emplace({std::move(k),std::forward<Args>(args)...});
}