std::swap(std::set)(3)
π NAME
std::swap(std::set) β ok bestie, this is literally the std::swap that's custom-built for std::set β¨ (like, the C++ Standard Library one, section 3 of the manual, iykyk π)
πΈ Synopsis
So the way this works: it lives in the header <set>, and there's a version for before C++17 and a version for after. Both slay, they just have different vibes π
template< class Key, class Compare, class Alloc >
void swap( std::set<Key, Compare, Alloc>& lhs, (until C++17)
std::set<Key, Compare, Alloc>& rhs );
template< class Key, class Compare, class Alloc >
void swap( std::set<Key, Compare, Alloc>& lhs, (since C++17)
std::set<Key, Compare, Alloc>& rhs )
noexcept(/* see below */);
What it does, fr fr: it specializes the std::swap algorithm for std::set, and it swaps the contents of lhs and rhs π₯
And underneath? It just calls lhs.swap(rhs). That's it. That's the whole personality π
π«Ά Parameters
lhs,rhsβ the containers whose contents to swap. Yes, both of them. You need two π
β Return value
(none) β nothing, nada, it returns void, it's giving "my job here is done" energy π
π Complexity
Constant. O(1) babe, it's iconic, it does not care how big your sets are π
π¦ Exceptions
The noexcept specification (since C++17, of course β¨):
noexcept(noexcept(lhs.swap(rhs)))
So it's noexcept exactly when lhs.swap(rhs) is noexcept. Vibe check passed β
π Example
Run this code, bestie, it's a whole little story about Alice and Bob π
// Run this code
#include <algorithm>
#include <iostream>
#include <set>
int main()
{
std::set<int> alice{1, 2, 3};
std::set<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
Look at them go π₯Ή Alice got Bob's numbers, Bob got Alice's, everybody ate π
π See also
swapβ swaps the contents (public member function) π§ β the member-function version of the same idea, if you're feeling classy
πΈ Category:
- conditionally noexcept π
ngl this one's short and sweet and lowkey perfect β swap your sets, keep your complexity constant, and never look back π
ok that's the whole page bestie, mwah π«Ά β this gem comes from http://cppreference.com, version 2024.06.10, and it's std::swap(std::set)(3), signing off β¨ππ
π¦ 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