0

In C++, is it a bad thing to use + for string concatenation? For example below,

string str = "";
int n = 10;
for (int i = 0; i < n; i++) {
  str += i + '0';
}

what is the time complexity for this code snippet? Is it O(n)? Does the string + operator in C++ like a vector's push_back and it dynamically grow itself if necessary when adding an item at the end so that the avg time is constant?

Update: One more question: if I need to append char to string but without knowing what is the length ahead, what is the best way to do it if it is not using + operator? I know in Java, we have stringbuilder, do we have similar thing c++ std?

bunny
  • 1,797
  • 8
  • 29
  • 58
  • 1
    Probably yes, there is no guarantee though: https://en.cppreference.com/w/cpp/string/basic_string/operator%2B%3D. Have you tried benchmarking your code? – Alan Birtles Aug 13 '20 at 06:20
  • Doubt it is `n`, perhaps `log n * n`. Many factors come into play. But with such small `n`, performance differences are not likely to be seen. – chux - Reinstate Monica Aug 13 '20 at 06:32
  • Make sure the 1st argument is `std::string` not `char[]` or `const char[]`. For example `str += "hello" + i + '0';` won't work. – David C. Rankin Aug 13 '20 at 06:47

3 Answers3

1

Does the string += operator in C++ like a vector's push_back() ...?

No, the operator+=() for std::string calls the append() and returns this.

Suppose a program:

#include <iostream>

int main(void) {
    std::string str1 = "Hello";
    std::string str2 = "World";
    str1 += str2;
    std::cout << str1;
}

Notice the syntax:

str1 += str2;

The operator+=() here will call the overloaded operator += from the String class:

basic_string& operator+=(const basic_string& __str)
      { return this->append(__str); }

Clearly, we can see here append() function is used. It's not push_back().

Exception: In Libstdc++ (which is part of GCC is written in C++ dependent upon Glibc), the passed parameter is char and applies push_back() function on the call of operator+=().

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • 1
    Note that the argument passed to `operator+` is `char`, not `std::string`. In `libstdc++`, `operator+=` with a `char` argument [calls](https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/bits/basic_string.h#L1163) `this->push_back`. – Evg Aug 13 '20 at 07:08
  • @Evg I see, I didn't know about `libstdc++`'s string manipulation and its overloaded operators. Edited. – Rohan Bari Aug 13 '20 at 07:51
  • It is not about `libstdc++`. In OP's code the type of `operator+=` argument is `int`. `int` can be implicitly converted into `char`, but it can't be converted into `std::string`. So your example with two strings is irrelevant to the question, and the conclusion that `operator+=` calls `append()` is wrong in general. `operator+=` has several overloads and they do different things. – Evg Aug 13 '20 at 07:57
  • @Evg `i + '0'` is resulted as a numeric character and then the char is assigned. – Rohan Bari Aug 13 '20 at 08:07
  • `str += some_str` and `str += some_char` call *different* overloads. – Evg Aug 13 '20 at 08:13
1

I like operator+ for std::string since it is simple and easy to understand code.

However, there might be frequent reallocation of memory if you concatenate too many, and every time reallocation occurs, copy of memory also happens. I prefer calling reserve() which allocates enough memory in advance, and concatenate strings.

string str;
int n = 10;
str.reserve(n);
for (int i = 0; i < n; i++) {
  str += i + '0';
}
John Park
  • 1,644
  • 1
  • 12
  • 17
0
  • Here is a general explanation about string: https://stackoverflow.com/a/9132610/13292734.

  • In your case is θ(n) and not O(n), because of the explanation in the link I added above.

  • But remember, sometimes it can be tricky, if the string that you allocated are n - k addresses for the string, and you would like to add the n - k + 1 char.

    For example: when you have 543 chars in the string and you want to add the 544th char to the string.

    It will make a problem and you would not have enough memory and it will add another address to store the n - k + 1 char but it will copy the whole string and will add the 544th char. In the end, it still O(n), but if you need a high performance, you have to take care about it.

gera verbun
  • 285
  • 3
  • 6