0

How can I effectively merge two strings? I know only standard concatenation with "+" - str3 = str1 + str2, but this way is not memory-effective, because a new string is created every time.

Sergey
  • 51
  • 2
  • 1
    fastest way might be to to use `+=` iirc `+=` resizes the string and copies the second at the end of first. `str1 += str2` –  Sep 10 '21 at 23:16

1 Answers1

0

There is std::basic_stringstream for that.

But if you only need to merge 2 strings, just append them.

Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27
  • `append ()` and `+=` are the same? –  Sep 10 '21 at 23:20
  • 1
    @KPCT they are certainly different things (function and operator), but one may be implemented by using another. – Vlad Feinstein Sep 10 '21 at 23:23
  • 1
    lol I know diff btw them, but internally aren't they the same. `+=` –  Sep 10 '21 at 23:25
  • @KPCT you are correct, the disassembly shows identical code, both are using `std::basic_string,std::allocator >::_Reallocate_grow_by<,char const *,unsigned int> (0401AA0h)` – Vlad Feinstein Sep 10 '21 at 23:32
  • 1
    Quoth the Standard: [Effects: Equivalent to: `return append(str);`](http://eel.is/c++draft/string.op.append#1) – user4581301 Sep 10 '21 at 23:33
  • @KPCT great, thank you for that link! However, `equivalent effect` is not `the same`, right? – Vlad Feinstein Sep 10 '21 at 23:35
  • No, It just means they have to do the exact same thing. How they get there is not formally defined. Probably A calls B, and when the compiler's done the intermediary call has been optimized out. – user4581301 Sep 10 '21 at 23:40
  • 1
    Here's GCC's take: `basic_string& operator+=(const basic_string& __str) { return this->append(__str); }` – user4581301 Sep 10 '21 at 23:41
  • @user4581301 right, as I commented above: `one may be implemented by using another`. Why the downvote? – Vlad Feinstein Sep 10 '21 at 23:47
  • 1
    Beats the fork out of me. I'll downvote at the drop of a hat, but I don't see anything wrong with your answer. – user4581301 Sep 10 '21 at 23:48
  • 1
    @VladFeinstein it was not me it was user4581301, but I remembered that I had this conversation few years back w someone. –  Sep 11 '21 at 00:42