可以更改std :: string容量进行优化吗? [英] Can std::string capacity be changed for optimisation?

查看:367
本文介绍了可以更改std :: string容量进行优化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以更改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);但是,这些都不能保证给你一个 capacity()   / code>匹配 size()。从 GotW#54 


有些实现可能会选择将容量略微上升到下一个更大的内部块大小,结果是容量实际上会稍微大于大小。



Can the std::string capacity be changed to optimise it?

For example:

std::string name0 = "ABCDEABCDEABCDEF";
int cap = name0.capacity();  //cap = 31
int size = name0.size();     //size = 16

Okay, this is perfectly fine for a couple of strings in memory, but what if there are thousands? This wastes a lot of memory. Isn't it then better to use char* so you can control how much memory is allocated for the specific string?

(I know some people will ask why are there thousands of strings in memory, but I would like to stick to my question of asking if the string capacity can be optimised?)

解决方案

If you're asking how to reduce capacity() so that it matches size(), then C++11 added shrink_to_fit() for this purpose, but be aware that it is a non-binding request, so implementations are allowed to ignore it.

name0.shrink_to_fit();

Or there's the trick of creating a temporary string and swapping:

std::string(name0.begin(), name0.end()).swap(name0);

However, neither of these are guaranteed to give you a capacity() that matches size(). From 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.

这篇关于可以更改std :: string容量进行优化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆