简体   繁体   English

如何在 C++ 11 及更高版本中将 std::map 和 std::unordered_map 的资源手动释放为 std::vector

[英]How to release resources of std::map and std::unordered_map manually as std::vector in C++ 11 and higher

Assume we have a vector std::vector<int> v and let's assume that some resources are allocated to it.假设我们有一个向量std::vector<int> v并假设一些资源分配给它。 To my knowledge, v.clear() and v.shrink_to_fit() releases all resources allocated to v .据我所知, v.clear()v.shrink_to_fit()释放分配给v所有资源。 I am wondering if there exist similar operations for std::map and std::unordered_map that release all resources manually.我想知道是否存在手动释放所有资源的std::mapstd::unordered_map类似操作。 I can only find a member function clear() for these two templates.我只能找到这两个模板的成员函数clear() Can someone explain why there is no shrink_to_fit() for the latter two templates?有人可以解释为什么后两个模板没有shrink_to_fit()吗?

There is no shrink_to_fit() in std::map , because it would be useless. std::map没有shrink_to_fit() ,因为它没用。

In std::vector , to ensure amortized constant insertion time required by standard, implementation can allocate more memory than is currently necessary for future storage (so that it doesn't have to reallocate everything each push_back() ).std::vector ,为了确保标准所需的摊销常量插入时间,实现可以分配比当前存储所需的更多的内存(这样它不必重新分配每个push_back()所有内容)。 Most implementations allocate 2*size() if current capacity() would be exceeded.如果超过当前capacity()大多数实现会分配2*size()

shrink_to_fit() asks to release that extra memory to make size() == capacity() (but it's not guaranteed that this will actually happen). shrink_to_fit()要求释放额外的内存以使size() == capacity() (但不能保证这会实际发生)。

Now, std::map is usually implemented as a red-black tree.现在, std::map通常实现为红黑树。 Adding an element into such structure is just creating new node and a bit of pointer magic.在这样的结构中添加一个元素只是创建新节点和一点指针魔法。 It will not involve reallocation of other nodes and you cannot speed it up by pre-allocating some memory.它不会涉及其他节点的重新分配,并且您无法通过预先分配一些内存来加速它。 shrink_to_fit() doesn't make sense, because there is nothing to shrink. shrink_to_fit()没有意义,因为没有什么可以缩小的。

Update after dewaffled 's comment: For std::unordered_map there's a rehash() method which may decrease size of hash table by recalculating it, but similarly to shrink_to_fit() it's not a guaranteed result.dewaffled的评论之后更新:对于std::unordered_map有一个rehash()方法,它可以通过重新计算来减小哈希表的大小,但与shrink_to_fit()类似,它不是保证结果。

I'm going to assume you're talking about dynamic maps;我假设你在谈论动态地图; the shrink_to_fit() wouldn't make sense because the map is only as big as its linked elements. shrink_to_fit() 没有意义,因为地图仅与其链接元素一样大。 My understanding is that there isn't 'empty' nodes for a map, like you could have empty fields in a vector.我的理解是地图没有“空”节点,就像向量中可能有空字段一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM