function template
std::swap (forward_list)
<forward_list>
template <class T, class Alloc>
void swap ( forward_list<T,Alloc>& lhs, forward_list<T,Alloc>& rhs );
Exchanges the contents of two forward_list containers
The contents of container lhs are exchanged with those of rhs. Both container objects must be of the same type (same template parameters), although sizes may differ.
After the call to this member function, the elements in lhs are those which were in rhs before the call, and the elements of rhs are those which were in lhs. All iterators, references and pointers remain valid for the swapped objects.
This is an overload of the generic algorithm swap that improves its performance by using move semantics (i.e., the containers exchange references to their data, without actually performing any copies). Behaves as if lhs.swap(rhs) was called.
Parameters
- lhs,rhs
- forward_list containers (to the left- and right-hand side of the operator, respectively), having both the same template parameters (T and Alloc).
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
// swap (forward_list overload)
#include <iostream>
#include <forward_list>
int main ()
{
std::forward_list<int> first = {10, 20, 30};
std::forward_list<int> second = {100, 200};
std::forward_list<int>::iterator it;
swap(first,second);
std::cout << "first contains:";
for (int& x: first) std::cout << " " << x;
std::cout << std::endl;
std::cout << "second contains:";
for (int& x: second) std::cout << " " << x;
std::cout << std::endl;
return 0;
}
|
Output:
first contains: 100 200
second contains: 10 20 30
|
Iterator validity
All iterators, pointers and references remain valid, but now are referring to elements in the other container, and iterate in it.
See also
- forward_list::swap
- Swap content (public member function)
- swap
- Exchange values of two objects (function template)
- swap_ranges
- Exchange values of two ranges (function template)