如果 std::map 被清除,是否确保内存被释放

If a std::map is cleared is it ensured, that the memory is deallocated

如果 std::vector vecvec.clear() 清除,分配的内存不能立即释放。向量的 size 将为零,但 capacity will/can 保持不变。

这是一种非常有益的行为,因为可以清除一个大向量并为其分配新值,而不需要昂贵的内存 de/allocation。内存碎片整理也将减少。

可以使用 vec.shrink_to_fit() shrink_to_fit 强制执行。

std::mapclear函数,但没有shrink_to_fit。在 clear 之后存储地图所需的内存会怎样?

cppreference.com 表示 map.clear() 擦除容器中的所有元素。此调用后,size() returns 归零。

One can enforce that with vec.shrink_to_fit() shrink_to_fit.

实际上,shrink_to_fit 不会强制 释放内存。它只是允许它。允许实现不释放。

If a std::map is cleared is it ensured, that the memory is deallocated

没有。标准容器保证释放内存的唯一情况是它们被销毁时。

Map 没有 vector 所具有的容量概念,因此它不需要 shrink_to_fit。清除后的映射与清除后的矢量处于相同的情况 + shrink_to_fit:它不需要分配任何内存...但也不禁止分配它。