std::vector如何处理可变长度的std::string
How does std::vector deal with variable length std::string?
- 我们可以通过写向量来构造一个向量来存储一堆字符串,但字符串可以是可变长度的,向量如何处理
- 我还测试了一个演示,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)
获得),而不考虑字符数。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL