Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prepend std::string

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.

like image 355
zeboidlund Avatar asked Dec 12 '11 00:12

zeboidlund


People also ask

What is std :: string& in C++?

C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.


2 Answers

There actually is a similar function to the non-existing std::string::push_front, see the below example.


Documentation of std::string::insert

#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; } 

output:

hello world 

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::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).

like image 146
Filip Roséen - refp Avatar answered Oct 01 '22 16:10

Filip Roséen - refp


myString.insert(0, otherString); 

Let the Standard Template Library writers worry about efficiency; make use of all their hours of work rather than re-programming the wheel.

This way does both of those.

As long as the STL implementation you are using was thought through you'll have efficient code. If you're using a badly written STL, you have bigger problems anyway :)

like image 23
matiu Avatar answered Oct 01 '22 17:10

matiu