在 C++ 中将 char 连接到字符串时会发生什么?
What goes on when you concatenate a char to a string in C++?
例如,下面的代码反转了一个字符串,但是当我将每个字符添加到一个字符串中时实际发生了什么?有效率吗?它是每次都创建一个新的字符数组,还是每次填满时都将大小加倍,还是?:
#include <iostream>
#include <stack>
using namespace std;
int main()
{
string test = "testing";
stack<char> first;
for(int i = 0; test[i]; i++)
{
first.push(test[i]);
}
string reversed;
int i=0;
while(!first.empty())
{
reversed += first.top();
first.pop();
}
cout << test << reversed;
}
是的,代码效率低下。您应该使用 std::reverse. But if you still want to stick with your approach, use std::string::reserve 来增加字符串的容量。
string reversed;
reversed.capacity(test.size());
当您将字符逐个添加到 std::vector
和 std::string
时,它们会在容量因常数因子耗尽时调整大小。 (通常为 2,但可能不同)
这 exponential growth 确保插入成本渐近恒定。
当一个字符串添加到另一个字符串时,在 + 运算符的情况下,结果字符串被移动构造。
字符串a("hello");
a+="goodmorning";
一个字符串在下面使用一个char缓冲区,并且在构造时将大小设置为默认值time.You可以在连接期间使用reserve.But更改它,如果超过保留大小,则缓冲区必须延长。
例如,下面的代码反转了一个字符串,但是当我将每个字符添加到一个字符串中时实际发生了什么?有效率吗?它是每次都创建一个新的字符数组,还是每次填满时都将大小加倍,还是?:
#include <iostream>
#include <stack>
using namespace std;
int main()
{
string test = "testing";
stack<char> first;
for(int i = 0; test[i]; i++)
{
first.push(test[i]);
}
string reversed;
int i=0;
while(!first.empty())
{
reversed += first.top();
first.pop();
}
cout << test << reversed;
}
是的,代码效率低下。您应该使用 std::reverse. But if you still want to stick with your approach, use std::string::reserve 来增加字符串的容量。
string reversed;
reversed.capacity(test.size());
当您将字符逐个添加到 std::vector
和 std::string
时,它们会在容量因常数因子耗尽时调整大小。 (通常为 2,但可能不同)
这 exponential growth 确保插入成本渐近恒定。
当一个字符串添加到另一个字符串时,在 + 运算符的情况下,结果字符串被移动构造。
字符串a("hello"); a+="goodmorning";
一个字符串在下面使用一个char缓冲区,并且在构造时将大小设置为默认值time.You可以在连接期间使用reserve.But更改它,如果超过保留大小,则缓冲区必须延长。