在C++11中从C++17重新实现std::map::try_emplace()
Re-implementing std::map::try_emplace() from C++17 in C++11?
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)...});
}
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- std::unique_ptr 在 try-catch 块中未捕获取消引用异常
- 如何在读写时禁用std::iostream try catch