std::map::try_emplace()看起来非常方便和有效,但它只适用于C++ 17.是否可以在C++ 11中重新实现它?
template <class... Args>
pair<iterator, bool> try_emplace(const key_type& k, Args&&... args);
Run Code Online (Sandbox Code Playgroud)
对于有序地图,您可以通过以下方式接近行为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};
}
Run Code Online (Sandbox Code Playgroud)
对于无序地图,您无法使用lower_bound.您可以将其替换find为测试,并使用key_eq(),以获得功能版本,但在插入的情况下将执行重复查找.Sp纯粹在算法复杂性方面说,这个新成员函数在无序情况下更加重要,用户目前无法仅使用公共API实现.但增加的便利性同样适用于这两种情况.