std::swap(s...ordered_map)(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸŽ€ NAME πŸŽ€

std::swap(std::unordered_map) β€” and yes bestie, the other side is also std::swap(std::unordered_map). That’s the whole name. Iconic.

Manual page vibes: std::swap(std::unordered_map)(3), from the C++ Standard Libary. 🫢


✨ Synopsis ✨

Defined in header <unordered_map>

First overload, tagged (since C++11) and (until C++17):

template< class Key, class T, class Hash, class KeyEqual, class Alloc >
void swap( std::unordered_map<Key, T, Hash, KeyEqual, Alloc>& lhs,
           std::unordered_map<Key, T, Hash, KeyEqual, Alloc>& rhs );

Second overload, tagged (since C++17):

template< class Key, class T, class Hash, class KeyEqual, class Alloc >
void swap( std::unordered_map<Key, T, Hash, KeyEqual, Alloc>& lhs,
           std::unordered_map<Key, T, Hash, KeyEqual, Alloc>& rhs )
    noexcept(/* see below */);

This specializes the std::swap algorithm for std::unordered_map. It swaps the contents of lhs and rhs. And the way it does that? It calls lhs.swap(rhs). Slay. πŸ’…


πŸ¦‹ Parameters πŸ¦‹

  • lhs, rhs β€” containers whose contents to swap. Literally the two besties exchanging their whole vibe. πŸ’–

🌸 Return value 🌸

(none) β€” nothing comes back, bestie. It’s a void situation. πŸ™ˆ


⭐ Complexity ⭐

Constant. That’s the whole energy: constant. Lowkey perfect. πŸ”₯


πŸ’€ Exceptions πŸ’€

noexcept specification: (since C++17) noexcept(noexcept(lhs.swap(rhs)))

No cap, that’s the exact spec. 🫢


🧚 Example 🧚

// Run this code

#include <algorithm>
#include <iostream>
#include <unordered_map>

int main()
{
    std::unordered_map<int, char> alice{{1, 'a'}, {2, 'b'}, {3, 'c'}};
    std::unordered_map<int, char> bob{{7, 'Z'}, {8, 'Y'}, {9, 'X'}, {10, 'W'}};

    auto print = [](std::pair<const int, char>& n)
    {
        std::cout << ' ' << n.first << ':' << n.second;
    };

    // Print state before swap
    std::cout << "Alice:";
    std::for_each(alice.begin(), alice.end(), print);
    std::cout << "\n" "Bob  :";
    std::for_each(bob.begin(), bob.end(), print);
    std::cout << '\n';

    std::cout << "-- SWAP\n";
    std::swap(alice, bob);

    // Print state after swap
    std::cout << "Alice:";
    std::for_each(alice.begin(), alice.end(), print);
    std::cout << "\n" "Bob  :";
    std::for_each(bob.begin(), bob.end(), print);
    std::cout << '\n';
}

Possible output:

Alice: 1:a 2:b 3:c
Bob  : 7:Z 8:Y 9:X 10:W
-- SWAP
Alice: 7:Z 8:Y 9:X 10:W
Bob  : 1:a 2:b 3:c

🌈 See also 🌈

  • swap swaps the contents β€” public member function. That’s the member-function bestie. 🫢

πŸ‘‘ Category πŸ‘‘

  • * conditionally noexcept

Source/version/date: http://cppreference.com, 2024.06.10, std::swap(s...ordered_map)(3) β€” bye bestie, go swap something iconic πŸ’–βœ¨

πŸ“¦ where this page comes from