Spec-Zone.ru › C++

std::map<Key,T,Compare,Allocator>::swap

void swap( map& other );
(до C++17)
void swap( map& other ) noexcept(/* see below */);
(с C++17)

Меняет содержимое контейнера с содержимым other. Не вызывает никаких операций перемещения, копирования или обмена для отдельных элементов.

Все итераторы и ссылки остаются действительными. Итератор end() становится недействительным.

Объекты Compare должны быть обмениваемыми, и они обмениваются с помощью неквалифицированного вызова нечленного swap.

Если std::allocator_traits<allocator_type>::propagate_on_container_swap::value является true, то аллокаторы обмениваются с помощью неквалифицированного вызова нечленного swap. В противном случае они не обмениваются (и если get_allocator() != other.get_allocator(), поведение не определено).

(с C++11)

Параметры

other - контейнер, с которым обмениваются содержимым

Возвращаемое значение

(нет)

Исключения

Любое исключение, выброшенное при обмене объектами Compare.

(до C++17)
noexcept спецификация:
noexcept(std::allocator_traits<Allocator>::is_always_equal::value
&& std::is_nothrow_swappable<Compare>::value)
(с C++17)

Сложность

Постоянная.

Пример

#include <iostream>
#include <string>
#include <utility>
#include <map>
 
// print out a std::pair
template<class Os, class U, class V>
Os& operator<<(Os& os, const std::pair<U, V>& p)
{
    return os << p.first << ':' << p.second;
}
 
// print out a container
template<class Os, class Co>
Os& operator<<(Os& os, const Co& co)
{
    os << '{';
    for (auto const& i : co)
        os << ' ' << i;
    return os << " }\n";
}
 
int main()
{
    std::map<std::string, std::string>
        m1{{"γ", "gamma"}, {"β", "beta"}, {"α", "alpha"}, {"γ", "gamma"}},
        m2{{"ε", "epsilon"}, {"δ", "delta"}, {"ε", "epsilon"}};
 
    const auto& ref = *(m1.begin());
    const auto iter = std::next(m1.cbegin());
 
    std::cout << "──────── before swap ────────\n"
              << "m1: " << m1 << "m2: " << m2 << "ref: " << ref
              << "\niter: " << *iter << '\n';
 
    m1.swap(m2);
 
    std::cout << "──────── after swap ────────\n"
              << "m1: " << m1 << "m2: " << m2 << "ref: " << ref
              << "\niter: " << *iter << '\n';
 
    // Note that every iterator referring to an element in one container before
    // the swap refers to the same element in the other container after the swap.
    // Same is true for references.
}

Вывод:

──────── before swap ────────
m1: { α:alpha β:beta γ:gamma }
m2: { δ:delta ε:epsilon }
ref: α:alpha
iter: β:beta
──────── after swap ────────
m1: { δ:delta ε:epsilon }
m2: { α:alpha β:beta γ:gamma }
ref: α:alpha
iter: β:beta

См. также

std::swap(std::map)
специализирует алгоритм std::swap
(функция-шаблон)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/container/map/swap

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API