1

If i want to insert the same character in a string a number of times that the user enters For example:

int n=30; string s=""; for(int i=0; i<n; i++) { s=s+"M"; } 

is there a more efficient way to make the same process in less time? because if n is a big number it will take the program quite long time to run

3 Answers 3

4

According : http://www.cplusplus.com/reference/string/string/append/ Case n°5 : Filling a string

str.append (14, 'd'); 

Will append 14 times the character 'd' in your string

Sign up to request clarification or add additional context in comments.

2 Comments

i was just about to write the same thing. kudos :)
This is still linear in count though.
2

Not sure if it's faster, but it's surely of a better style:

s += std::string('M', n); 

Comments

0

The answer is a more likely no, there isn't a more efficient way of doing it. Most operations will actually be linear in count. Including constructing an alternative string, appending to it using std::string::append and even std::fill. A good way to maybe get a speed up though is by using s.push_back('M') and by possibly making a reserve call but even then it won't be noticeably faster, if at all.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.