cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : Strings library : swap
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
Strings library
char_traits
classes:
· string
global functions:
· getline
· operator+
· operator<<
· operator>>
· comparison operators
· swap

-

swap function
void swap ( string& lhs, string& rhs);
<string>

Swap contents of two strings

Swaps the contents of the string objects lhs and rhs, such that after the call to this function, the contents of rhs are those which were in lhs before the call, and the contents of lhs are those which were in rhs.

Notice that string objects implement a member function also called swap; In fact, this global function effectively calls:

lhs.swap(rhs);

Parameters

lhs
a string object to be swapped.
rhs
the other string object to be swapped.

Return value

none

Example

// swap strings
#include <iostream>
#include <string>
using namespace std;

main ()
{
  string buyer ("money");
  string seller ("goods");

  cout << "Before swap, buyer has " << buyer;
  cout << " and seller has " << seller << endl;

  swap (buyer,seller);

  cout << " After swap, buyer has " << buyer;
  cout << " and seller has " << seller << endl;

  return 0;
}

Output:

Before swap, buyer has money and seller has goods
After swap, buyer has goods and seller has money

Basic template declaration

template<class charT, chass traits, class Allocator>
  void swap ( basic_string<charT,traits,Allocator>& lhs,
              basic_string<charT,traits,Allocator>& rhs);

See also

string::swap Swap contents with another string (public member function)
string::replace Replace part of string (public member function)
string::assign Assign content to string (public member function)

© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us