std::swap(std::deque)(3)
π std::swap(std::deque) β bestie edition
ok so this is a page straight out of the C++ Standard Libary man pages (yes that's how they spell it, no I will not be fixing it, we respect the source π«Ά), and today's main character is std::swap(std::deque).
β¨ NAME β¨
std::swap(std::deque) β which is, and I cannot stress this enough, literally std::swap(std::deque) π
πΈ SYNOPSIS πΈ
First things first, this whole situation lives in the header <deque>:
Defined in header <deque>
and here's the signature, in all its two-flavours-of-C++ glory:
template< class T, class Alloc >
void swap( std::deque<T, Alloc>& lhs, (until C++17)
std::deque<T, Alloc>& rhs );
template< class T, class Alloc >
void swap( std::deque<T, Alloc>& lhs, (since C++17)
std::deque<T, Alloc>& rhs )
noexcept(/* see below */);
So what's the vibe? This is a specialization of the std::swap algorithm, but specifically for std::deque π. It swaps the contents of lhs and rhs, and the way it does that is by calling lhs.swap(rhs). That's it. That's the whole bit, and honestly? slay.
π Parameters π
lhs,rhsβ the containers whose contents we're swapping. that's it, that's the parameter list, they're just two deques getting their whole thing rearranged π«
π¦ Return value π¦
(none) β nothing, nada, zero, the void. it does the thing and gives you nothing back, and that's iconic behaviour β¨
β Complexity β
Constant. lowkey the best complexity tier, no cap π₯
π Exceptions π
noexcept specification, and this bit is since C++17:
noexcept(noexcept(lhs.swap(rhs)))
π Example π
Run this code π§
#include <algorithm>
#include <iostream>
#include <deque>
int main()
{
std::deque<int> alice{1, 2, 3};
std::deque<int> bob{7, 8, 9, 10};
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 10
-- SWAP
Alice: 7 8 9 10
Bob : 1 2 3
and that's the swap. Alice and Bob traded whole personalities and the program is thriving ππ
π₯ See also π₯
swapβ swaps the contents (it's a public member function, iykyk π)
π Category π
- * conditionally noexcept
fr fr that's the whole page, nothing skipped, nothing invented. go swap your deques, bestie π«Ά
made with love from http://cppreference.com, dated 2024.06.10, and yes it's the std::swap(std::deque)(3) page in the C++ Standard Libary, 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