c语言中swap函数

介绍 (Introduction)

In this tutorial, we are going to learn the swap() function in C++ programming language. Swapping is a simple operation in C++ which basically is the exchange of data or values among two variables of any data type. Considering both the variables are of the same data type.

在本教程中,我们将学习C ++编程语言中的swap()函数。 交换是C ++中的一个简单操作,基本上是在任何数据类型的两个变量之间交换数据或值。 考虑到两个变量的数据类型相同。

So, let us get right into the function and its working.

因此,让我们直接了解该函数及其功能。

在C ++中swap()函数的工作 (Working of the swap() function in C++)

The swap() function in C++, from the standard library, is a function that directly swaps values between two given variables of the same types. Let us look at the syntax for using the same:

来自标准库的C ++中swap()函数是一个在两个相同类型的给定变量之间直接交换值的函数。 让我们看看使用相同的语法:

Syntax,

语法


std::swap( a , b );

Here:

这里:

  • a and b, both are variables of the same data type,ab都是相同数据类型的变量,
  • We pass both of them to the swap() function and the values at their respective addresses are exchanged among themselves,我们将它们都传递给swap()函数,并且它们各自地址处的值相互交换
  • a now stores the value b previously had, whereas, b has the value which a prior to swapping stored.一个现在存储值b以前有,反之,b的交换存储之前,它的值。

Now, let us see how we can use the swap() function in C++.

现在,让我们看看如何在C ++中使用swap()函数。

如何在C ++中使用swap()函数 (How to use the swap() function in C++)

As we specified earlier, the swap() function from the standard library in C++ can swap values of any data type including int, float, string, etc. and even data structures like arrays, stacks, and queues, etc.

正如我们之前所指定的, C ++中标准库中的swap()函数可以交换任何数据类型的值,包括int,float,string等,甚至数据结构,如数组,堆栈和队列等。

So now we are going to look at some examples where we try to swap integers, strings as well as arrays in order to have a clear understanding.

因此,现在我们来看一些示例,在这些示例中我们尝试交换整数字符串以及数组 ,以使您有一个清晰的认识。

1.在C ++中使用swap()交换两个整数值 (1. Swapping two integer values using swap() in C++)

First, let us consider the swapping of two integer values using the function. Look at the code given below carefully,

首先,让我们考虑使用函数交换两个整数值。 仔细看看下面给出的代码,


#include <iostream>
using namespace std;
int main()
{ //values before swappingint val1 = 2;int val2 = 5;//swapping using swap()swap(val1, val2);//values after swappingcout<<"New value of val1 = "<<val1<<endl;cout<<"New value of val2 = "<<val2<<endl;return 0;
}

Output:

输出


New value of val1 = 5
New value of val2 = 2

Here,

这里,

  • val1 and val2 are initialized with values 2 and 5 respectivelyval1val2分别用值2和5初始化
  • After we pass both of them to the std::swap() function the values of the same are printed to confirm the swapping在将它们都传递给std::swap()函数之后,将打印它们的值以确认交换
  • As we can see, val1 now holds 5 whereas, val2 stores 2. That is, we successfully swapped both the values如我们所见, val1现在保存5,val2存储2 。 也就是说,我们成功地交换了两个值

2.使用swap()交换两个字符串 (2. Swapping of two strings using swap())

Now, let us see how we can swap two string objects from the string header file.

现在,让我们看看如何从字符串头文件中交换两个字符串对象。


#include <iostream>
#include <string>
using namespace std;
int main()
{ //strings before swappingstring string1 = "String 1";string string2 = "String 2";//swapping strings using swap()swap(string1, string2);//strings after swappingcout<<"New value of string1 = "<<string1<<endl;cout<<"New value of string2 = "<<string2<<endl;return 0;
}

Output:

输出

String Swapping
字符串交换

Clearly, from the output given below, our swapping is successful. Both the strings string1 and string2 values are exchanged.

显然,从下面给出的输出中,我们的交换是成功的。 字符串string1string2值都被交换。

3.使用swap()交换两个array() (3. Swapping two arrays() using swap())

We can even swap arrays using the swap() function. Let us see how

我们甚至可以使用swap()函数交换数组 。 让我们看看


#include <iostream>
using namespace std;
int main()
{ //arrays before swappingint array1[3] = {1,2,3};int array2[3] = {2,4,6};int i;//swapping arrays using swap()swap(array1, array2);//arrays after swappingcout<<"New value of array1 = "<<endl;for(i=0;i<3;i++)cout<<" "<<array1[i];cout<<"\nNew value of array2 = "<<endl;for(i=0;i<3;i++)cout<<" "<<array2[i];return 0;
}

Output:

输出

Swapping Arrays
交换阵列

In the code above:

在上面的代码中:

  • array1 and array2 are the two given arraysarray1array2是两个给定的数组
  • We pass both the arrays to the swap() function for swapping我们将两个数组都传递给swap()函数进行交换
  • After swapping, as we can see from the output, the contents of both the arrays are now exchanged交换之后,从输出中可以看到,两个数组的内容现在都已交换

Note: Here we have used examples of swapping integers, strings and arrays for clear understanding. But the functions swapping ability is not limited to these data types. We can also swap other data structures like stacks and queues and other data types

注意 :这里我们使用交换整数,字符串和数组的示例来进行清楚的理解。 但功能交换能力并不局限于这些数据类型。 我们还可以交换其他数据结构,例如堆栈队列以及其他数据类型

在C ++中使用swap()函数时出错 (Error while using the swap() function in C++)

While using the swap() function if we try to swap the values of two variables belonging to two different data types. The following error is thrown by the compiler.

在使用swap()函数时,如果我们尝试交换属于两种不同数据类型的两个变量的值。 编译器将引发以下错误。


#include <iostream>
using namespace std;
int main()
{ //arrays before swappingint array1[3] = {1,2,3};char array2[3] = {'1','2','3'};int i;//swapping arrays using swap() we get error hereswap( array1, array2);//arrays after swappingcout<<"New value of array1 = "<<endl;for(i=0;i<3;i++)cout<<" "<<array1[i];cout<<"\nNew value of array2 = "<<endl;for(i=0;i<3;i++)cout<<" "<<array2[i];return 0;
}

Error:

错误


C:\Users\sneha\Desktop\C++.cpp    [Error] no matching function for call to 'swap(int [3], char [3])'

Hence, for avoiding this type of conflict, we must make sure that the data types of the variables are the same.

因此,为了避免这种类型的冲突,我们必须确保变量的数据类型相同。

结论 (Conclusion)

Hope this tutorial helps to understand the use as well as the working of the swap() function in C++. For any questions feel free to use the comments below.

希望本教程有助于理解C ++中 swap()函数的用法和工作原理 。 如有任何疑问,请随时使用以下评论。

参考资料 (References)

  • Stackoverflow question on simple swap function in C++,关于C ++中简单交换函数的 Stackoverflow问题,
  • Stackoverflow question on How does the standard library implement std::swap() in C++关于标准库如何在C ++中实现std :: swap()的 Stackoverflow问题

翻译自: https://www.journaldev.com/37269/swap-function-in-c-plus-plus

c语言中swap函数

c语言中swap函数_C ++中的swap()函数相关推荐

  1. c语言中math的库函数,C语言中math.h库中的常用函数

    C语言中math.h库中的常用函数 int abs(int i) 返回整型参数i的绝对值 double cabs(struct complex znum) 返回复数znum的绝对值 double fa ...

  2. scala 函数中嵌套函数_Scala中的嵌套函数 用法和示例

    scala 函数中嵌套函数 Scala中的嵌套函数 (Nested functions in Scala) A nested function is defined as a function whi ...

  3. oracle中转换函数,Oracle中的转换函数

    Oracle中的转换函数有三个,分别为to_char(),to_date(),to_number() 1.to_char()的用法 格式化当前的日期时间 select sysdate,to_char( ...

  4. c语言中exit函数_C ++中的exit()函数

    c语言中exit函数 介绍 (Introduction) Today we'll learn about exit() in C++. We know we can break out of loop ...

  5. c语言中struct和c++中class实例对比

    前言 实现游戏中简单的打怪升级的功能 c语言中的struct #include <stdio.h>typedef void(*Train)(struct player*, int); ty ...

  6. c语言中fflush_在C中使用fflush()

    c语言中fflush In this article, we'll take a look at how we can use the fflush() function in C. 在本文中,我们将 ...

  7. C语言中sizeof测量形参中数组的长度

    在C语言中,若我们在主函数中定义了一个数组,并给数组赋予了初值,在之后,若有函数需要调用,且需要用到该数组的长度,该怎么来操作. 在下面的代码中定义了一个数组,在main函数中用sizeof函数来计算 ...

  8. python语言中mod_mod在python中怎么用

    MOD是取模运算符. 语法 MOD ( a, b) 通常情况下取模运算(mod)和求余(rem)运算被混为一谈,因为在大多数的编程语言里,都用'%'符号表示取模或者求余运算.在这里要提醒大家要十分注意 ...

  9. c语言中getenv的作用,C语言putenv()函数和getenv()函数的使用详解

    C语言putenv()函数和getenv()函数的使用详解 C语言putenv()函数:改变或增加环境变量头文件: #include4 定义函数: int putenv(const char * st ...

最新文章

  1. Linux进程及进程管理命令
  2. 各位最近找我索要CCNA200-120的资源的同志些
  3. java 做计算器 百度云_用Java做一个简单的计算器
  4. VS Tools for AI全攻略(2)低配置虚拟机也能玩转深度学习,无需NC/NV系列
  5. Redis 集群_主从复制_哨兵模型
  6. [转]Aptana Studio 3配置Python开发环境图文教程
  7. android8 测试,Android 8.0 Oreo 国内可用测试平台上线
  8. mysql手机客户端_图解MySQL索引--B-Tree(B+Tree)
  9. 计算机插本2a院校,广东省专插本2A院校有哪些
  10. maven创建web工程,完善目录结构时出现HttpServlet等类的找不到的bug
  11. silverlight控件动画状态的过渡
  12. 车辆路径规划问题(VRP问题)
  13. java报告模板_JAVA报告模板.doc
  14. stm32f103呼吸灯(PWM脉冲宽度调制)
  15. 【Java】绘图入门和机制,绘图方法演示(绘制坦克)
  16. ms-sql数据类型和access数据类型大全
  17. docker 简单教程
  18. MySQL-Test-Run测试工具
  19. 利用Python产生加密表和解密表
  20. ATRESplayer PREMIUM携手华为提升用户体验,突破浏览量历史记录

热门文章

  1. 江苏省计算机一级理论题难吗,江苏省计算机一级理论题库第一章题号
  2. lol大洋洲服务器账号,英雄联盟大洋洲官网
  3. 【必备算法】哈希算法:七种应用及场景示例
  4. LVGL---线条(lv_line)
  5. JAVA高级特性(六)——IO流(第一讲)
  6. JMX详解以及使用示例
  7. 独孤思维:表情包的副业项目,让你副业收入倍增
  8. java 日期格式化 英文_Java SimpleDateFormat 中英文时间格式化转换
  9. 思想的肖像:亚里士多德(ARISTOTLE )(3)
  10. GAT项目新需求:加油管理修改