std::swap(std::array)(3)
π NAME π
std::swap(std::array) β std::swap(std::array), literally. Bestie, this is page std::swap(std::array)(3) from the C++ Standard Libary manual (yes, that spelling, itβs iconic), and weβre about to make swapping arrays make sense. No cap. π«Ά
β¨ Synopsis β¨
Defined in header <array>
template< class T, std::size_t N >
(since C++11)
void swap( std::array<T, N>& lhs, (until C++17)
std::array<T, N>& rhs );
template< class T, std::size_t N >
void swap( std::array<T, N>& lhs, (since C++17)
std::array<T, N>& rhs ) (constexpr since C++20)
noexcept(/* see below */);
Okay so this overload specializes the std::swap algorithm for std::array. It swaps the contents of lhs and rhs, and it does that by calling lhs.swap(rhs). Slay. π
This overload participates in overload resolution only if N == 0 or β since C++17 β std::is_swappable_v<T> is true. Thatβs the vibe check for whether it even shows up. π₯
πΈ Parameters πΈ
lhs,rhsβ the containers whose contents youβre swapping, bestie. Thatβs it. Thatβs the whole parameter moment. π
π Return value π
(none) β literally no return value. It swaps and dips. π«Ά
π¦ Complexity π¦
Linear in size of the container. Highkey grows with how many elements are in there. π§
π Exceptions π
The noexcept specification is, since C++17:
noexcept(noexcept(lhs.swap(rhs)))
So yes, itβs giving βI might be noexcept, depending on what lhs.swap(rhs) is doing.β Conditionally iconic. β¨
π₯ Example π₯
// Run this code
#include <algorithm>
#include <iostream>
#include <array>
int main()
{
std::array<int, 3> alice{1, 2, 3};
std::array<int, 3> bob{7, 8, 9};
auto print = [](const int& n) { std::cout << ' ' << n; };
// 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';
}
Output:
Alice: 1 2 3
Bob : 7 8 9
-- SWAP
Alice: 7 8 9
Bob : 1 2 3
They really swapped. Alice got Bobβs numbers, Bob got Aliceβs numbers, and the group chat is shook. ππ
π See also π
swapβ swaps the contents (public member function). Bestie, itβs the member-function bestie of this whole situation. π
π·οΈ Category π·οΈ
- conditionally noexcept β itβs giving conditional confidence. π
Alright bestie, signing off with the official cute footer energy: source/version line is http://cppreference.com, date is 2024.06.10, and the page is std::swap(std::array)(3). Mwah. ππ
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms