C++ .swap()
In C++, the .swap() method for strings is used to exchange the contents of two strings efficiently. It is commonly used in scenarios like optimizing performance during reordering, implementing the copy-and-swap idiom in custom classes, or quickly clearing a string by swapping it with an empty one.
Syntax
string1.swap(string2);
Parameters:
string2: Anotherstd::stringobject whose contents will be swapped withstring1.
Return value:
This method performs the swap in-place and does not return a value.
After calling the .swap() method, the contents of string1 and string2 are exchanged: string1 now holds the original contents of string2, and string2 holds the original contents of string1.
Example
In this example, the .swap() method is used to exchange the contents of two strings, a and b:
#include <iostream>#include <string>int main() {std::string a = "apple";std::string b = "banana";std::cout << "Before swap:\n";std::cout << "a = " << a << "\n";std::cout << "b = " << b << "\n";// Swap the contents of a and ba.swap(b);std::cout << "\nAfter swap:\n";std::cout << "a = " << a << "\n";std::cout << "b = " << b << "\n";return 0;}
The output for this will be:
Before swap:a = appleb = bananaAfter swap:a = bananab = apple
Codebyte Example
In this codebyte example, .swap() is called on the place1 and place2 strings:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours