问题描述
预设 std :: string
的最有效方式是什么?是否值得写出一个完整的函数来这样做,或者它只需要1 - 2行?我没有看到任何与 std :: string :: push_front
有关的内容。
What is the most efficient way to prepend std::string
? Is it worth writing out an entire function to do so, or would it take only 1 - 2 lines? I'm not seeing anything related to an std::string::push_front
.
推荐答案
其实有一个类似于不存在的 std :: string :: push_front
的函数,参见下面的例子。
There actually is a similar function to the non-existing std::string::push_front
, see the below example.
#include <iostream>
#include <string>
int
main (int argc, char *argv[])
{
std::string s1 (" world");
std::string s2 ("ello");
s1.insert (0, s2); // insert the contents of s2 at offset 0 in s1
s1.insert (0, 1, 'h'); // insert one (1) 'h' at offset 0 in s1
std::cout << s1 << std::endl;
}
输出:
hello world
因为前面带有数据的字符串可能需要重新分配和复制/移动现有数据,你可以通过使用 std :: string :: reserve (以前分配更多的内存)。
Since prepending a string with data might require both reallocation and copy/move of existing data you can get some performance benefits by getting rid of the reallocation part by using
std::string::reserve
(to allocate more memory before hand).
复制/移动数据是不可避免的,除非你定义自己的自定义类
std :: string
分配一个大缓冲区,并将第一个内容放在此内存缓冲区的中心。
The copy/move of data is sadly quite inevitable, unless you define your own custom made class that acts like
std::string
that allocates a large buffer and places the first content in the center of this memory buffer.
然后,如果缓冲区足够大,则可以预先添加和附加数据,而不重新分配和移动数据。
Then you can both prepend and append data without reallocation and moving data, if the buffer is large enough that is. Copying from source to destination is still, obviously, required though.
如果你有一个缓冲区,你知道你会添加数据比你附加一个好的替代方法是将字符串向后存储,并在需要时将其反转(如果这是更罕见的)。
If you have a buffer in which you know you will prepend data more often than you append a good alternative is to store the string backwards, and reversing it when needed (if that is more rare).
这篇关于前缀std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!