Algorithm Swap Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Swap Function

Algorithm Swap Function

BLUF: Mastering Algorithm Swap Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Swap Function

C++ is renowned for its efficiency. Learn how Algorithm Swap Function enables low-level control and high-performance computing in the tutorial below.

The swap function in C++ algorithms exchanges or switches the values of two referenced containers.

Syntax

Example

template<class T> void swap(T& a, T& b);

Parameter

a : It is the first container with some value.

b : It is another container with some value.

Return value

The function simply exchanges the values between two containers without returning any output.

Example 1

Example

#include <iostream> 

#include <algorithm>

#include <vector>   

int main () 

{

  int a=14, b=9;

  std::swap(a,b);

  std::vector<int> sg (4,a), ss (6,b);      

  std::swap(sg,ss);                          

  std::cout << "sg contains:";

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

    std::cout << ' ' << *ti;

  std::cout << '\n';

  return 0;

}

Output:

Output

sg contains: 14 14 14 14 14 14

Example 2

Example

#include <bits/stdc++.h>

using namespace std;

int main()

{

	int ss = 9;

	int sg = 14;

	cout << "Value of ss before swapping: " << ss << endl;

	cout << "Value of sg before swapping: " << sg << endl;

	swap(ss, sg);

	cout << "Value of ss after swapping: " << ss << endl;

	cout << "Value of sg after swapping: " << sg << endl;

	return 0;

}

Output:

Output

Value of ss before swapping: 9

Value of sg before swapping: 14

Value of ss after swapping: 14

Value of sg after swapping: 9

Complexity

For arrays, the function exhibits a complexity of N due to the need to swap each element individually. Conversely, for non-array data structures, the function maintains a constant complexity.

Data races

Both the containers are undergo modification

Exceptions

The function will raise an exception if any of the container elements also raises an exception.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience