std::map::try_emplace() http://en.cppreference.com/w/cpp/container/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 来实现。但增加的便利同样适用于这两种情况。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)