C++ String Library - swap



Description

It exchanges the content of the container by the content of str, which is another string object. Lengths may differ.

Declaration

Following is the declaration for std::string::swap.

 void swap (string& str); 

C++11

 void swap (string& str); 

C++14

 void swap (string& str); 

Parameters

str − It is a string object.

Return Value

none

Exceptions

if an exception is thrown, there are no changes in the string.

Example

In below example for std::string::swap.

 #include <iostream> #include <string> main () { std::string buyer ("money"); std::string seller ("goods"); std::cout << "Before the swap, buyer has " << buyer; std::cout << " and seller has " << seller << '\n'; seller.swap (buyer); std::cout << " After the swap, buyer has " << buyer; std::cout << " and seller has " << seller << '\n'; return 0; } 

The sample output should be like this −

 Before the swap, buyer has money and seller has goods After the swap, buyer has goods and seller has money 
string.htm
Advertisements