std::string::push_back vs. std::string::operator+=

  • Thread starter Matthias =?ISO-8859-1?Q?K=E4ppler?=
  • Start date
M

Matthias =?ISO-8859-1?Q?K=E4ppler?=

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
 
R

Rob Williscroft

Matthias Käppler wrote in in
comp.lang.c++:
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.
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.

Whichever you want, they both do the same thing.

Rob.
 
J

Jonathan Mcdougall

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;

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top