Compartilhar via


basic_string::swap

Exchange the contents of two strings.

void swap(
    basic_string<CharType, Traits, Allocator>& _Str
);

Parameters

  • _Str
    The source string whose elements are to be exchanged with those in the destination string.

Remarks

If the strings being swapped have the same allocator object, the swap member function:

  • Occurs in constant time.

  • Throws no exceptions.

  • Invalidates no references, pointers, or iterators that designate elements in the two strings.

Otherwise, it performs a number of element assignments and constructor calls proportional to the number of elements in the two controlled sequences.

Example

// basic_string_swap.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( ) 
{
   using namespace std;

   // Declaring an objects of type basic_string<char>
   string s1 ( "Tweedledee" );
   string s2 ( "Tweedledum" );
   cout << "Before swapping string s1 and s2:" << endl;
   cout << " The basic_string s1 = " << s1 << "." << endl;
   cout << " The basic_string s2 = " << s2 << "." << endl;

   s1.swap ( s2 );
   cout << "After swapping string s1 and s2:" << endl;
   cout << " The basic_string s1 = " << s1 << "." << endl;
   cout << " The basic_string s2 = " << s2 << "." << endl;
}
Before swapping string s1 and s2:
 The basic_string s1 = Tweedledee.
 The basic_string s2 = Tweedledum.
After swapping string s1 and s2:
 The basic_string s1 = Tweedledum.
 The basic_string s2 = Tweedledee.

Requirements

Header: <string>

Namespace: std

See Also

Reference

basic_string Class

Other Resources

basic_string Members