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交换。

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-vector-swap-function.html

来源:LearnFk无涯教程网

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

技术教程推荐

趣谈网络协议 -〔刘超〕

玩转Git三剑客 -〔苏玲〕

编辑训练营 -〔总编室〕

乔新亮的CTO成长复盘 -〔乔新亮〕

eBPF核心技术与实战 -〔倪朋飞〕

遗留系统现代化实战 -〔姚琪琳〕

B端体验设计入门课 -〔林远宏(汤圆)〕

结构思考力 · 透过结构看表达 -〔李忠秋〕

LangChain 实战课 -〔黄佳〕

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