Skip to main content

std::string swap() method

// Non const version only
constexpr void swap( basic_string& other ) noexcept(/* see below */);

Exchanges the contents of the string with those of other.

Possible invalidation

All iterators and references may be invalidated.

Undefined Behavior

The behavior is undefined

if Allocator does not propagate on swap and the allocators of *this and other are unequal.

Parameters​

  • other - the string to exchange the contents with

Return value​

(none)

Complexity​

Constant - O(1).

Exceptions​

noexcept specification:

noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value
|| std::allocator_traits<Allocator>::is_always_equal::value)

Example​

Main.cpp
#include <string>
#include <iostream>

int main()
{
std::string a = "AAA";
std::string b = "BBB";

std::cout << "before swap" << '\n';
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';

a.swap(b);

std::cout << "after swap" << '\n';
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';
}
Output
before swap
a: AAA
b: BBB
after swap
a: BBB
b: AAA
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::string swap() method

// Non const version only
constexpr void swap( basic_string& other ) noexcept(/* see below */);

Exchanges the contents of the string with those of other.

Possible invalidation

All iterators and references may be invalidated.

Undefined Behavior

The behavior is undefined

if Allocator does not propagate on swap and the allocators of *this and other are unequal.

Parameters​

  • other - the string to exchange the contents with

Return value​

(none)

Complexity​

Constant - O(1).

Exceptions​

noexcept specification:

noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value
|| std::allocator_traits<Allocator>::is_always_equal::value)

Example​

Main.cpp
#include <string>
#include <iostream>

int main()
{
std::string a = "AAA";
std::string b = "BBB";

std::cout << "before swap" << '\n';
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';

a.swap(b);

std::cout << "after swap" << '\n';
std::cout << "a: " << a << '\n';
std::cout << "b: " << b << '\n';
}
Output
before swap
a: AAA
b: BBB
after swap
a: BBB
b: AAA
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.