字符串的容量和大小不同 [英] Different Between Capacity And Size in String

查看:101
本文介绍了字符串的容量和大小不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

here is a code :

#include <iostream>
#include <string>
using namespace std;
int main() {
    std::string s1 = "Hello";
    cout << ".size() returns " << s1.size() << endl;
    cout << ".capacity() returns " << s1.capacity() << endl;
    s1.append("!");
    cout << ".size() returns " << s1.size() << endl;
    cout << ".capacity() returns " << s1.capacity() << endl;
    return 0;
}


这是输出:

有时大小= 6,容量= 12....
为什么与众不同?

容量和大小有什么区别?

预先感谢.


This is an Output :

sometimes Size=6 and Capacity=12....
Why Its different?

What is different between Capacity and Size?

Thanks in advance.

推荐答案

容量是字符串可以容纳的字符数,大小是字符串存在时的实际大小.
Capacity is how many characters the string can hold, and size is the actual size of the string as it exists.


基于字符串的当前内容,在创建或调整字符串大小时计算容量.这允许字符串内容的少量增加,而无需分配新的存储块.所使用的实际值是该类的内部.
Capacity is calculated when the string is created or resized, based on its current content. This allows a small increase in the string''s contents without the necessity of allocating a new memory block. The actual value used is internal to the class.


所有STL容器都根据需求动态分配内存.
但是分配的内存总是大于实际需要的内存,这样它就可以应付将来向容器中添加的内容,而无需分配额外的内存.

这样做是因为内存分配非常耗时.
同样,过多的内存分配将不必要地浪费内存.

因此,两者之间是平衡的.

因此,size返回容器内容的实际大小,而capacity返回当前分配的总内存.

试试这个-
All STL containers allocate memory dynamically based on demand.
But the memory allocated is always greater than what is actually required so that it cope with future additions to the container without allocating additional memory.

This is done because memory allocation is time consuming.
Also too much memory allocation will unnecessarily waste memory.

So there is a balance between the 2.

So size returns the actual size of the contents of the container and capacity returns the total memory currently allocated.

Try this -
std::string s1;
for (int i = 0; i < 100; ++i)
{
    s1.append("");
    cout << "Size = " << s1.size() << ", Capacity = " << s1.capacity() << endl;
}


这篇关于字符串的容量和大小不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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