Best way to create a string containing multiple copies of another string

I want to create a function that takes a string and an integer as parameters and returns a string containing the string parameter repeated the specified number of times.

For instance:

std::string MakeDuplicate( const std::string& str, int x ) { ... } 

Call MakeDuplicate( "abc", 3 ); will return "abcabcabc" .

I know I can do this by simply looping a few times, but I'm sure there should be a better way.

+4
source share
4 answers

I don't see a loop problem, just make a backup first:

 std::string MakeDuplicate( const std::string& str, int x ) { std::string newstr; newstr.reserve(str.length()*x); // prevents multiple reallocations // loop... return newstr; } 
+18
source

At some point, it should be a cycle. You can hide the loop in some bizarre language idiom, but in the end you will have to go in cycles.

+7
source

For the little "x" simple loop your friend. For large β€œx” and relatively short β€œstr”, we can think of a β€œsmarter” solution by reusing an already concatenated string.

 std::string MakeDuplicate( const std::string& str, unsigned int x ) { std::string newstr; if (x>0) { unsigned int y = 2; newstr.reserve(str.length()*x); newstr.append(str); while (y<x) { newstr.append(newstr); y*=2; } newstr.append(newstr.c_str(), (xy/2)*str.length()); } return newstr; } 

Or something like that: o) (I think it can be written better, but there is an idea).

EDIT: I was interested and conducted several tests comparing the three solutions on my laptop with the visual studio (reuse option, simple loop with pre-distribution, simple copy and loop-1 without prior use). Expected results: for a small version of the pre-location x (<10), as a rule, the fastest, the pre-location was not the minimum bit slower, since the high speed of the acceleration of the "reuse" version is really significant (log n vs n complexity). It's nice, I just can’t come up with any real problem that could use it: o)

+4
source

There is an alternative to a loop called recursion and tail- recursion recursion - this is the most pleasant variety, since you can theoretically do this until the end of time - just like a loop: D

ps, tail recursion is often the syntactic sugar for a loop - however, in the case of procedural languages ​​(C ++), the compiler is usually lost, so tail recursion is not optimized, and you may run out of memory (but if you wrote a recursion that ran out of memory, than you have big problems): D

more downvotes please !!

Recursion

obviously, it is not a construction used in computer science for the same work as the cycle

+2
source

All Articles