Книга: Standard Template Library Programmer
swap
Разделы на этой странице:
swap
Category: algorithms
Component type: function
Prototype
template <class Assignable>
void swap(Assignable& a, Assignable& b);
Description
Assigns the contents of a to b and the contents of b to a. This is used as a primitive operation by many other algorithms.
Definition
Defined in the standard header algorithm, and in the nonstandard backward-compatibility header algo.h.
Requirements on types
• Assignable is a model of Assignable.
Preconditions
None.
Complexity
Amortized constant time. [1] [2]
Example
int x = 1;
int y = 2;
assert(x == 1 && y == 2);
swap(x, y);
assert(x == 2 && y == 1);
Notes
[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.
See also
iter_swap, swap_ranges
- Очистка swap при выключении компьютера
- Пример 28-2. Создание файла подкачки (swapfile), с помощью
- Swap
- iter_swap
- swap_ranges
- Список литературы
- Пропуск параметров типа
- Фактические аргументы
- Использование модификаторов параметров ref и out
- 2.3.3. Ручное создание разделов
- 12.5.4. Журнал прокси-сервера squid
- Use the Contents of the