如何在 std::map 中添加元素自己进行分配
How to add element in std::map doing allocation oneself?
我问题背后的目的是使用std::map
(即插入,删除,访问),并保证std::map
实现不会引发异常。
删除不是问题,如果仔细使用东西(例如,没有检查就没有at
),则访问也不是问题。
但插入是另一个问题。在此代码中:
#include <map>
struct foo{};
int main()
{
std::map<int, foo> my_map;
my_map.insert(std::pair<int, foo>(42, foo{}));
}
my_map
做一些分配,如果没有更多的内存,就抛出。
现在,我想要的是一种执行此操作的方法:
#include <map>
struct foo{};
int main()
{
std::map<int, foo> my_map;
auto my_new_pair{ new std::pair<int, foo>(42, foo{}) };
if (my_new_pair) // ok, we could build the node
{
my_map.insert(my_new_pair); // no allocation, my_map only takes the "ownership" of my_new_pair
}
}
但是没有这种超载的insert
.
你们有解决方案吗?
我问题背后的目的是使用 std::map(即插入, 删除,访问),并保证不会引发异常 标准::地图实现。
std::allocator
如果在实例化
std::map <
键, T, Com=std::less <
键 >
, 分配器= std::allocator<...>
>
;
那么您不能做出任何例外保证。 在inserts
或emplace
.
23.2.1/8: 除非另有说明,否则本条款中定义的所有容器 使用分配器获取内存
我不明白在大多数 STL 实现中如何在没有内存分配的情况下进行插入,因为它们主要使用带有堆分配节点的红黑树。您可能希望使用从现有内存池分配的自定义分配器,并且没有例外保证。或者编写自己的容器。
使用节点提取和转题:
{
std::map<int, foo> staging_map;
staging_map.emplace(42, foo{});
real_map.insert(staging_map.extract(42)); // cannot throw
}
你不是"自己"做分配,但你基本上可以用这种方法获得一个预先分配的映射节点,你可以用它来达到你自己的目的,直到你准备好将其插入到映射中,例如:
auto nh = staging_map.extract(42);
// Done initializing.
// use nh freely
real_map.insert(std::move(nh)); // guaranteed to work
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 当我们push_back元素时,std::vector 什么时候会放大自己?
- stl 中是否有任何数据结构可以在 O(1) 或 O(log n) 中插入元素,我可以在其上编写自己的bin_searc
- 如何在 std::map 中添加元素自己进行分配
- 试图用c++编写我自己的链表实现,在点击列表中的3个元素后编写segfault代码
- 如果我自己不分配数组元素,数组元素的值是多少
- 在元素自己的析构函数中擦除指向静态向量中元素的指针
- 元素如何在vector中找到自己的索引?
- 如何在C++中将字符串中的元素转换为它自己的字符串?