Class string
provides member function swap for swapping string
s. Figure 19.4 swaps two string
s. Lines 9–10 declare and initialize string
s first
and second
. Each string
is then output. Line 15 uses string
member function swap
to swap the values of first
and second
. The two string
s are printed again to confirm that they were indeed swapped. The string
member function swap
is useful for implementing programs that sort strings.
1 // Fig. 19.4: Fig19_04.cpp
2 // Using the swap function to swap two strings.
3 #include <iostream>
4 #include <string>
5 using namespace std;
6
7 int main()
8 {
9 string first( "one" );
10 string second( "two" );
11
12 // output strings
13 cout << "Before swap:
first: " << first << "
second: " << second;
14
15 first.swap( second ); // swap strings
16
17 cout << "
After swap:
first: " << first
18 << "
second: " << second << endl;
19 } // end main
Before swap:
first: one
second: two
After swap:
first: two
second: one