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

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

技术教程推荐

深入浅出gRPC -〔李林锋〕

算法面试通关40讲 -〔覃超〕

iOS开发高手课 -〔戴铭〕

Flink核心技术与实战 -〔张利兵〕

WebAssembly入门课 -〔于航〕

Go 并发编程实战课 -〔晁岳攀(鸟窝)〕

小马哥讲Spring AOP编程思想 -〔小马哥〕

如何读懂一首诗 -〔王天博〕

手把手带你写一门编程语言 -〔宫文学〕

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