| Category: algorithms | Component type: function |
template <class Assignable> void swap(Assignable& a, Assignable& b);
int x = 1; int y = 2; assert(x == 1 && y == 2); swap(x, y); assert(x == 2 && y == 1);
[1] The time required to swap two objects of type T will obviously depend on the type; "constant time" does not mean that performance will be the same for an 8-bit char as for a 128-bit complex<double>.
[2] This implementation of swap makes one call to a copy constructor and two calls to an assignment operator; roughly, then, it should be expected to take about the same amount of time as three assignments. In many cases, however, it is possible to write a specialized version of swap that is far more efficient. Consider, for example, swapping two vector<double>s each of which has N elements. The unspecialized version requires 3*N assignments of double, but a specialized version requires only nine pointer assignments. This is important because swap is used as a primitive operation in many other STL algorithms, and because containers of containers (list<vector<char> >, for example) are very common. The STL includes specialized versions of swap for all container classes. User-defined types should also provide specialized versions of swap whenever it is possible to write one that is more efficient than the general version.
./usr/share/doc/stl-manual/html/swap_ranges.html 0000644 0000000 0000000 00000010403 10447635250 020615 0 ustar root root
| Category: algorithms | Component type: function |
template <class ForwardIterator1, class ForwardIterator2> ForwardIterator2 swap_ranges(ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2);
vector<int> V1, V2; V1.push_back(1); V1.push_back(2); V2.push_back(3); V2.push_back(4); assert(V1[0] == 1 && V1[1] == 2 && V2[0] == 3 && V2[1] == 4); swap_ranges(V1.begin(), V1.end(), V2.begin()); assert(V1[0] == 3 && V1[1] == 4 && V2[0] == 1 && V2[1] == 2);