std::vector如何处理可变长度的std::string

How does std::vector deal with variable length std::string?

本文关键字:std string 处理 vector 何处理      更新时间:2023-10-16
  1. 我们可以通过写向量来构造一个向量来存储一堆字符串,但字符串可以是可变长度的,向量如何处理
  2. 我还测试了一个演示,test[0]以0x2508cb0开头,test[1]以0x2508cb8开头,但两个地址的差异和test[0]的容量似乎不一样

int main(){

vector<string> test;
test.push_back("tes3235235et");
test.push_back("135125151241241241");
cout << test[0].capacity() << endl;
cout << test[1].capacity() << endl;
cout << &(test[0]) << endl;
cout << &(test[1]) << endl;
return 0;

}

输出:

12
18
0x2508cb0
0x2508cb8

向量不需要处理这个问题,因为字符串处理这个问题。就像std::vector一样,std::string将其元素存储在动态分配的内存中。字符不是字符串对象本身的一部分(小字符串优化的情况除外),而是通过指针引用的。字符串对象的实际大小在编译时设置,并且对于所有字符串都是相同的(并且可以通过sizeof(std::string)获得),而不考虑字符数。