C++ 向量 中的 swap()函数

首页 / C++入门教程 / C++ 向量 中的 swap()函数

此函数用于交换两个向量中指定的元素。

swap - 语法

考虑两个向量v1和v2。语法为:

v1.swap(v2);

swap - 范围

v2  -  v2是一个向量,其值将与另一个向量交换。

swap - 返回值

它不返回任何值。

无涯教程网

swap - 例子1

让我们看一个简单的例子。

#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int>  v1={1,2,3,4,5};
vector<int>  v2={6,7,8,9,10};
cout<<"Before swapping,elements of v1 are :";
for (int i=0;i<v1.size();i++)
cout<<v1[i]<<" ";
cout<<'\n';
cout<<"Before swapping,elements of v2 are :";
for(int i=0;i<v2.size();i++)
cout<<v2[i]<<" ";
cout<<'\n';
v1.swap(v2);
cout<<"After swapping,elements of v1 are  :";
for(int i=0;i<v1.size();i++)
cout<<v1[i]<<" ";
cout<<'\n';
cout<<"After swapping,elements of v2 are:";
for(int i=0;i<v2.size();i++)
cout<<v2[i]<<" ";
return 0;
}

输出:

Before swapping,elements of v1 are :1 2 3 4 5 
Before swapping,elements of v2 are :6 7 8 9 10 
After swapping,elements of v1 are  :6 7 8 9 10 
After swapping,elements of v2 are :1 2 3 4 5

在此示例中,swap()函数将向量v1的元素与向量v2交换。

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

技术教程推荐

Linux实战技能100讲 -〔尹会生〕

SRE实战手册 -〔赵成〕

Web安全攻防实战 -〔王昊天〕

React Native 新架构实战课 -〔蒋宏伟〕

深入浅出可观测性 -〔翁一磊〕

超级访谈:对话玉伯 -〔玉伯〕

云原生架构与GitOps实战 -〔王炜〕

手把手带你写一个MiniSpring -〔郭屹〕

后端工程师的高阶面经 -〔邓明〕

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