可以改变std::string的容量来优化吗?
例如:
std::string name0 = "ABCDEABCDEABCDEF";
int cap = name0.capacity(); //cap = 31
int size = name0.size(); //size = 16
好的,这对于内存中的几个字符串来说完全没问题,但是如果有数千个怎么办?这会浪费很多内存。使用 char* 不是更好吗,这样您就可以控制为特定字符串分配多少内存?
(我知道有些人会问为什么内存中有几千个字符串,但我想坚持我的问题,问字符串容量是否可以优化?)
最佳答案
如果您询问如何减少capacity()
以便它匹配size()
,那么C++11 添加了shrink_to_fit()
为此目的,但要注意这是一个非约束性请求,因此允许实现忽略它。
name0.shrink_to_fit();
或者有创建临时字符串和交换的技巧:
std::string(name0.begin(), name0.end()).swap(name0);
但是,这些都不能保证为您提供匹配 size()
的 capacity()
。来自 GotW #54 :
Some implementations may choose to round up the capacity slightly to their next larger internal "chunk size," with the result that the capacity actually ends up being slightly larger than the size.
关于c++ - 可以更改 std::string 容量以进行优化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23935177/