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.
What is the most efficient way to prepend std::string ? Is it worth writing
Share
There actually is a similar function to the non-existing
std::string::push_front, see the below example.Documentation of std::string::insert
output:
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).The copy/move of data is sadly quite inevitable, unless you define your own custom made class that acts like
std::stringthat 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).