I know it is a common issue, but looking for references and other material I don't find a clear answer to this question.
Consider the following code:
#include <string> // ... // in a method std::string a = "Hello "; std::string b = "World"; std::string c = a + b;
The compiler tells me it cannot find an overloaded operator for char[dim]
.
Does it mean that in the string there is not a + operator?
But in several examples there is a situation like this one. If this is not the correct way to concat more strings, what is the best way?
Yes, in your case*1 string concatenation requires all characters to be copied, this is a O(N+M) operation (where N and M are the sizes of the input strings). M appends of the same word will trend to O(M^2) time therefor.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.
The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b .
If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues.
Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:
std::string c = "hello" + "world";
This doesn’t work because for C++ this seems like you’re trying to add two char
pointers. Instead, you need to convert at least one of the char*
literals to a std::string
. Either you can do what you’ve already posted in the question (as I said, this code will work) or you do the following:
std::string c = std::string("hello") + "world";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With