### Qualified's blog

By Qualified, history, 10 days ago, ,

I would always do if I wanted to insert 'a' into the beginning of the string.  reverse(s.begin(), s.end());   s += 'a';   reverse(s.begin(), s.end());  Is there a built-in function to insert a character in the beginning of a string?

• +8

 » 10 days ago, # |   0 You can use insert(index,string) to insert string at any position of your string. Examplestring s="odeforces"; s.insert(0,"c"); cout<
•  » » 10 days ago, # ^ |   0 Thanks, but do you know the time complexity of each? The built-in method and my method.
•  » » » 10 days ago, # ^ | ← Rev. 2 →   +24 Both methods are O(n) which is highly not recommended. Try to use deque instead. like: dequedq; A simple code that takes input from a string and then places an F before the string: dequedq; string s; cin>>s; for(int i=0;i
•  » » » » 10 days ago, # ^ | ← Rev. 2 →   +5 Thanks! BTW, you can just do  for(auto i: dq) { cout << i << " "; }
•  » » » » » 10 days ago, # ^ |   0 You are welcome!
•  » » » » » 10 days ago, # ^ | ← Rev. 2 →   +24 In the same vein, you can even do copy(s.begin(),s.end(),back_inserter(dq)); and copy(dq.begin(),dq.end(),ostream_iterator(cout)); and avoid writing loops completely.Edit: with spaces, it would be copy(dq.begin(),dq.end(),ostream_iterator(cout," ")); 
•  » » » » » » 10 days ago, # ^ |   0 Thanks!
 » 10 days ago, # |   +13 The simplest thing is to write s = 'a' + s. I'm not sure what is the complexity, but since it is just copying string I believe it cannot be bigger than linear.
•  » » 10 days ago, # ^ |   +24 It's O(n)
•  » » 10 days ago, # ^ | ← Rev. 2 →   0 I want it to put the character in the beginning of the string and not the end of the string. Thanks tho
•  » » » 10 days ago, # ^ |   0 This does put it at the begging of the string. Try it.
•  » » » » 10 days ago, # ^ |   0 Oh... That was my bad. I thought that you wrote s = s + 'a'. and not s = 'a' + s; Thanks!
•  » » » 7 days ago, # ^ |   0 General TIP : Complexity of adding char at the end is O(n) if you are doing s = s + 'a' and O(1) if you are doing s += 'a'.
•  » » » » 6 days ago, # ^ |   0 Really? Do think about allocating space for a new buffer 1 byte more than the existing one and copying all characters of the string into the buffer then storing the character 'a' at the end.
 » 9 days ago, # |   0 s='a'+s;