TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C++ algorithm swap() function

C++ algorithm swap() function tutorial for beginners and professionals with examples on adjacent_find(),any_of(), copy(), copy_if(), count(), count_if(), equal(), find(), find_end(), find_first_of(), find_if(), find_if_not(), for_each() etc.

<< Back to CPP

C++ Algorithm Functions swap()

C++ Algorithm swap() function swaps or say interchanges the values of two containers under reference.

Syntax

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 only swaps the values of two containers and does not return something.

Example 1

#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:

sg contains: 14 14 14 14 14 14

Example 2

#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:

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 has N complexity as the operation of swapping is individually performed on each element. For non array the function has constant complexity.

Data races

Both the containers are undergo modification

Exceptions

The function throws an exception if any of the container elements throws one.


Next Topic




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf