Discussion:
std::string::push_back vs. std::string::operator+=
(too old to reply)
Matthias Käppler
2004-11-22 20:45:58 UTC
Permalink
Hi,

I just browsed libstdc++6-doc and stumbled over a string operation I haven't
noticed before: string::push_back.
If for example I want to append single characters to an std::string, which
one would be better, or is there any difference at all:

mystr.push_back( c );

or

mystr += c;

Any ideas? I used to use the latter one.

Regards,
Matthias
Rob Williscroft
2004-11-23 01:39:41 UTC
Permalink
Post by Matthias Käppler
Hi,
I just browsed libstdc++6-doc and stumbled over a string operation I
haven't noticed before: string::push_back.
push_back() is there so that std::string conforms as "Back
Insertion Sequence".

Because its there you can use std::back_inserter with std::string
for example. Or any other generic algorithm that requires a back
insertion sequence.
Post by Matthias Käppler
If for example I want to append single characters to an std::string,
mystr.push_back( c );
or
mystr += c;
Any ideas? I used to use the latter one.
Whichever you want, they both do the same thing.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jonathan Mcdougall
2004-11-23 19:11:08 UTC
Permalink
Post by Matthias Käppler
I just browsed libstdc++6-doc and stumbled over a string operation I haven't
noticed before: string::push_back.
If for example I want to append single characters to an std::string, which
mystr.push_back( c );
or
mystr += c;
They behave the same way but logically they do different things.
push_back() is there because std::string is a container and operator +=
it there because it's a string. The same thing with size() and length().

Jonathan

Loading...