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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Matthias Käppler

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

    Hi,

    I just browsed libstdc++6-doc and stumbled over a string operation I haven't
    noticed before: string::push_ba ck.
    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

    #2
    Re: std::string::pu sh_back vs. std::string::op erator+=

    Matthias Käppler wrote in news:cntj5d$ooa $03$1@news.t-online.com in
    comp.lang.c++:
    [color=blue]
    > Hi,
    >
    > I just browsed libstdc++6-doc and stumbled over a string operation I
    > haven't noticed before: string::push_ba ck.[/color]

    push_back() is there so that std::string conforms as "Back
    Insertion Sequence".

    Because its there you can use std::back_inser ter with std::string
    for example. Or any other generic algorithm that requires a back
    insertion sequence.
    [color=blue]
    > 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.
    >[/color]

    Whichever you want, they both do the same thing.

    Rob.
    --

    Comment

    • Jonathan Mcdougall

      #3
      Re: std::string::pu sh_back vs. std::string::op erator+=

      > I just browsed libstdc++6-doc and stumbled over a string operation I haven't[color=blue]
      > noticed before: string::push_ba ck.
      > 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;
      >[/color]

      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

      Comment

      Working...