增加字符串的容量

Increase the capacity of a string

本文关键字:容量 字符串 增加      更新时间:2023-10-16

编写以下代码片段,以了解每个字符串追加操作将向字符串添加多少字节的内存。

#include <iostream>
#include <string>
#include <unordered_map>
#include <sys/time.h>
#include <arpa/inet.h>
using namespace std;
typedef unsigned short uint16;
typedef unsigned int uint;

int main (int argc, char *argv[]) {
    const char *p = NULL;
    string s = "";
    for (int i=0; i<1050; i++) {
        s += "a";
        if (s.c_str() != p) {
            printf("%5dn", i);
            p = s.c_str();
        }
    }
    return 0;
}

输出为

    0
    1
    2
    4
    8
   16
   32
   64
  128
  256
  512
 1024

因此,结果非常清楚地表明,它每次都会将字符串的存储量增加一倍(至少)。

问题是,如何将use指定的空间(比如2000字节)添加到现有字符串中,这样就可以在不触发free/malloc的情况下进行多次字符串附加。

谢谢。

您可以通过使用reserve()成员函数来实现这一点。请注意,它可能不会分配您要求的确切存储量(您可能会得到更多),但您在一次分配中至少会得到您要求的

阅读文档!

这就是std::string::reserve的作用