std::string swap() method
- od C++20
- od C++17
- do C++17
// Non const version only
constexpr void swap( basic_string& other ) noexcept(/* see below */);
// Non const version only
void swap( basic_string& other ) noexcept(/* see below */);
// Non-const version only
void swap( basic_string& other );
Exchanges the contents of the string with those of other
.
Possible invalidation
All iterators and references may be invalidated.
- od C++11
Undefined Behavior
The behavior is undefined
ifAllocator
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
- od C++17
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.
Hover to see the original license.