C++ 算法 中的 swap函数

首页 / C++入门教程 / C++ 算法 中的 swap函数

C++算法swap()函数交换或说互换引用下的两个集合的值。

swap - 语法

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

swap - 参数

a :这是第一个具有一定价值的集合。

b :这是另一个具有一定价值的集合。

swap - 返回值

该函数仅交换两个集合的值,并且不返回任何内容。

swap - 例子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;
}

输出:

sg contains: 14 14 14 14 14 14

swap - 例子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;
}

输出:

Value of ss before swapping: 9
Value of sg before swapping: 14
Value of ss after swapping: 14
Value of sg after swapping: 9

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

深入浅出计算机组成原理 -〔徐文浩〕

Java性能调优实战 -〔刘超〕

DevOps实战笔记 -〔石雪峰〕

后端技术面试 38 讲 -〔李智慧〕

系统性能调优必知必会 -〔陶辉〕

Linux内核技术实战课 -〔邵亚方〕

搞定音频技术 -〔冯建元 〕

手把手教你落地DDD -〔钟敬〕

结构会议力 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)