Reputation: 403
I would like to append a char to a std::string in C++. I can think of at least three ways to do it:
std::string s = "hello";
char c = '!';
s += c;
s.append(c);
s.push_back(c);
Also, if I want to add two strings, same question with:
std::string s1 = "hello ", s2 = "world";
s1.append(s2);
s1 += s2;
Upvotes: 1
Views: 281
Reputation: 106246
which one is considered best practice?
If you've written a template accepting a variety of container types including string, the containers' APIs may only have a subset of those methods in common - in which case it's good to use that.
For example:
template <typename Container>
void f(Container& c, int n)
{
if (n % 7) c.push_back(n);
}
This will work with anything that support push_back
- namely std::vector
, std::deque
, std::list
, std::string
. This contrasts with +=
and append
which - of the Standard Library containers - are only supported by std::string
.
Otherwise, do whatever you think's clearest to read - likely +=
.
is there a performance difference (C++11)?
No reason there would be in optimised code, though implementations aren't required by the Standard to ensure that.
(Talking about performance of unoptimised code is not often useful, but FWIW in unoptimised code it's possible one or more of these may be written in terms of another (i.e. it may call the other function), and if inlining isn't done then the less direct code may be ever-so-slightly slower: which that is may vary across implementations. It would be misguided to worry about this.)
Also, if I want to add two strings, same question [...]
For two std::string
s it's a little more complicated, as something like this...
template <typename Container, tyepname Value>
void append_twice(Container& c, const Value& v)
{
c.push_back(v);
c.push_back(v);
}
...could still be used for vector
, deque
, list
, and string
, but it does something semantically different for string by implicitly extracting and appending char
elements, so you might want to avoid supporting all the types if correct behaviour of later code in your algorithm depends on that difference between extracting the char
s and extracting the same string
elements from the container that were appended earlier.
Again there's no performance difference.
Upvotes: 2
Reputation: 71
The question is a matter of the compiler and personal taste and/or company coding style requirements. The over loaded operator probably resolves to your 2nd choice.
I would go with first one myself
Upvotes: 4