Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/string/basic string/swap"

From cppreference.com
< cpp‎ | string‎ | basic string
m (reorder)
m (See also: +)
Line 65: Line 65:
 
b: AAA
 
b: AAA
 
}}
 
}}
 +
 +
===See also===
 +
{{dsc begin}}
 +
{{dsc inc | cpp/algorithm/dsc swap}}
 +
{{dsc inc | cpp/algorithm/dsc swap_ranges}}
 +
{{dsc inc | cpp/string/basic_string_view/dsc {{SUBPAGENAMEE}}}}
 +
{{dsc end}}
  
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
 
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}

Revision as of 04:24, 4 May 2021

 
 
 
std::basic_string
Member functions
Element access
Iterators
Capacity
Modifiers
basic_string::swap
Search
Operations
Constants
Non-member functions
I/O
Comparison
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
Numeric conversions
(C++11)(C++11)(C++11)
(C++11)(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
Literals
Helper classes
Deduction guides (C++17)

 
void swap( basic_string& other );
(until C++17)
void swap( basic_string& other ) noexcept(/* see below */);
(since C++17)
(until C++20)
constexpr void swap( basic_string& other ) noexcept(/* see below */);
(since C++20)

Exchanges the contents of the string with those of other. All iterators and references may be invalidated.

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

(since C++11)

Contents

Parameters

other - string to exchange the contents with

Return value

(none)

Complexity

Constant.

Exceptions

noexcept specification:  
noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value
|| std::allocator_traits<Allocator>::is_always_equal::value)
(since C++17)

Example

#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

See also

swaps the values of two objects
(function template) [edit]
swaps two ranges of elements
(function template) [edit]
swaps the contents
(public member function of std::basic_string_view<CharT,Traits>) [edit]