Swap c что это

от admin

Функция SWAP в языке С: что это и как работает

Функция SWAP в С — простой способ обменять значения двух переменных, которые содержат одинаковые типы данных. Эта функция доступна из стандартной библиотеки. В основном ее применяют для работы с небольшими данными, потому что она несет в себе конструкцию из копирования значений переменных и обмена этих значений. Такая конструкция задействует определенный объем памяти. А это значит, что , если применить функцию SWAP в Си для работы с большими данными, с низится производительность программы.

Функция SWAP в С

Для простой реализации функции SWAP в Си из стандартной библиотеки можно воспользоваться следующим шаблоном:

#include <utility>

using std::swap;

int main() <

int x = 8;

int y = 9;

// после выполнения программы результат будет таким: x = 9, y = 8

>

Функция SWAP в С может применяться и в более сложных конструкциях, например:

#include <iostream>

#include <algorithm>

#include <vector>

int main () <

int a=100, b=200; //присваиваем значения переменным: a=100, b=200

std::swap(a,b); // функция swap меняет значения переменных: a=200, b=100

std::vector<int> foo (2,a), bar (3,b) //проводим операции: foo:2×200 bar:3×100

std::swap(foo, bar); //swap меняет значения операций: foo:3×100 bar:2×200

std:: cout < < “ foo содержит: “;

for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)

std::cout < < ` < < *it;

std::cout < < `\n`;

return 0;

>

После выполнени я э та программ а нам выдаст следующий результат:

foo содержит: 100 100 100

Функция SWAP в С работает не только с числами, но и с другими типами данных, например со строками:

#include <bits/stdc++.h>

using namespace std;

int main()

<

string a = “Функция“;

string b = “Программирование“;

cout << “Значение переменной «а» до применения функции SWAP: “ << a << endl;

cout << “Значение переменной «b» до применения функции SWAP: “ << b << endl;

swap (a, b);

cout < < “Значение переменной «а» после применения функции SWAP: “ << a << endl;

cout << “Значение переменной «b» после применения функции SWAP: “ << b << endl;

retorn 0;

>

Результат выполнения такой программы будет следующий:

Значение переменной «а» до применения функции SWAP: Функция

Значение переменной «b» до применения функции SWAP: Программирование

Значение переменной «а» после применения функции SWAP: Программирование

Значение переменной «b» после применения функции SWAP: Функция

Заключение

Функция SWAP в С работает с любыми типами данных. Чтобы она сработала, у переменных обязательно должно быть какое-то значение. Она ничего не возвращает, а просто меняет местами значения переменных.

Мы будем очень благодарны

если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.

Is there a built in swap function in C?

Is there any built in swap function in C which works without using a third variable?

Mat's user avatar

10 Answers 10

You can use this to swap two variable value without using third variable:

You can also check this:

Why do you not want to use a third variable? It’s the fastest way on the vast majority of architectures.

The XOR swap algorithm works without a third variable, but it is problematic in two ways:

  1. The variables must be distinct i.e. swap(&a, &a) will not work.
  2. It is slower in general.

It may sometimes be preferable to use the XOR swap if using a third variable would cause the stack to spill, but generally you aren’t in such a position to make that call.

To answer your question directly, no there is no swap function in standard C, although it would be trivial to write.

Assuming you want a C solotion, not a C++ one, you could make it a macro, at least using GCC extension to have it generic enough, something like

Читать:
Какой язык программирования используется в excel

beware of tricks like invocations swap(t[i++],i) ; to avoid them, use the address operator & . And you’ll better use a temporary (for integers, there is a famous and useless trick with exclusive-or).

PS: I’m using two local variables _x and _y (but I could have used one local variable only) for better readability, and perhaps also to enable more optimizations from the compiler.

std:: swap

std::swap may be specialized in namespace std for program-defined types, but such specializations are not found by ADL (the namespace std is not the associated namespace for the program-defined type).

The expected way to make a program-defined type swappable is to provide a non-member function swap in the same namespace as the type: see Swappable for details.

The following overloads are already provided by the standard library:

[edit] Example

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

Implement Swap Function in C

This article will explain several methods of how to implement the swap function in C.

Please enable JavaScript

Use Temporary Variable to Implement Swap Function in C

The swap function is a typical operation to conduct on variables. There is no C standard library function that provides the feature like C++ has std::swap function. In this article, we implement swap functions for integral values; namely, most of them take long int type arguments, but one can always define multiple prototypes for different types and ensure generic features using macro expansions. The following example demonstrates the swap function using the temporary variable. Note that, even though it is the easiest implementation, this one is relatively the fastest version among others listed below (when the compiler optimizations are used).

Use Arithmetic Operations to Implement Swap Function in C

Alternatively, one can implement a swap function using only addition and subtraction operations. We operate on passed pointers in the function, thus, modifying the argument values directly. In the main function, there is an if condition before the swap function is called to avoid invocation when the operands are equal.

Use Bitwise XOR Operation to Implement Swap Function in C

The most tricky and slightly complicated implementation of the swap function is where the bitwise XOR operation is used. Note that this version does not need a third variable like the previous example. At first, we store the XOR-ed result of the given integers in one of their places. Then, we XOR the stored value( y ) with the other integer and store the result in the latter’s place. Finally, both variables are XOR-ed once more time, and the result is stored in the firstly modified variable — y in this case. This implementation involves more machine code instructions when compiled without optimization flags, thus, yields a more compute-intensive solution.

Use Bitwise XOR Operation and Macros to Implement Swap Function in C

As demonstrated in the previous example, the XOR swap function can also be implemented as a function-like macro. Note that there needs to be a check if the two operands are the same object; otherwise, the macro assigns zero to the object, which results in the erroneous output. This check is implemented using ?: conditional, and only then do we execute the XOR swap algorithm similar to the previous implementation. Mind though, that this function-like macro can only process integral values.

Похожие статьи