stl swap函数_vector :: swap()函数以及C ++ STL中的示例

本文介绍了C++ STL中的vector::swap()函数,该函数用于交换两个向量的内容,即使它们的大小不同。通过包含<vector>头文件可以使用此功能。示例代码展示了如何在C++程序中应用vector::swap()。
摘要由CSDN通过智能技术生成

stl swap函数

C ++ vector :: swap()函数 (C++ vector::swap() function)

vector::swap() is a library function of "vector" header, it is used to swap the content of the vectors, it is called with a vector and accepts another vector as an argument and swaps their content. (Sizes of both of the vectors may differ).

vector :: swap()“ vector”头文件的库函数,用于交换向量的内容,用向量调用它并接受另一个向量作为参数并交换其内容。 (两个向量的大小可能不同)。

Note: To use vector, include <vector> header.

注意:要使用向量,请包含<vector>标头。

Syntax of vector::swap() function

vector :: swap()函数的语法

    vector::swap(vector& v);

Parameter(s): v – It is another vector to be swapped content with current vector.

参数: v –这是另一个要与当前向量交换内容的向量。

Return value: void – It returns nothing.

返回值: void –不返回任何内容。

Example:

例:

    Input:
    vector<int> v1{ 10, 20, 30, 40, 50 };
    vector<int> v2{ 100, 200, 300 };
    
    //swapping content of the vectors
    v1.swap(v2);

    Output:
    //if we print the values
    v1: 100 200 300
    v2: 10 20 30 40 50

C ++程序演示vector :: swap()函数的示例 (C++ program to demonstrate example of vector::swap() function)

//C++ STL program to demonstrate example of
//vector::erase() function

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    //vector declaration
    vector<int> v1{ 10, 20, 30, 40, 50 };
    vector<int> v2{ 100, 200, 300 };

    //printing the sizes and values of the vectors
    cout << "before swap() call..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "size of v2: " << v2.size() << endl;

    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    cout << "v2: ";
    for (int x : v2)
        cout << x << " ";
    cout << endl;

    //swapping the content of the vectors
    v1.swap(v2);

    //printing the sizes and values of the vectors
    cout << "after swap() call..." << endl;
    cout << "size of v1: " << v1.size() << endl;
    cout << "size of v2: " << v2.size() << endl;

    cout << "v1: ";
    for (int x : v1)
        cout << x << " ";
    cout << endl;

    cout << "v2: ";
    for (int x : v2)
        cout << x << " ";
    cout << endl;

    return 0;
}

Output

输出量

before swap() call...
size of v1: 5
size of v2: 3
v1: 10 20 30 40 50
v2: 100 200 300
after swap() call...
size of v1: 3
size of v2: 5
v1: 100 200 300
v2: 10 20 30 40 50

Reference: C++ vector::swap()

参考: C ++ vector :: swap()

翻译自: https://www.includehelp.com/stl/vector-swap-function-with-example.aspx

stl swap函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值