C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ swap()

C++ 算法函数swap()

C++ 算法swap()函数交换或说互换引用下的两个容器的值。

语法

template<class T> void swap(T& a, T& b);

参数

a : 它是第一个具有某些值的容器。
b : 这是另一个具有某些值的容器。

返回值

该函数仅交换两个容器的值,不返回任何内容。

示例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

示例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

复杂度

对于数组,该函数的复杂度为N,因为交换操作是在每个元素上单独执行的。对于非数组,该函数具有恒定的复杂性。

数据竞争

两个容器都经过修改

异常

如果任何容器元素抛出一个异常,该函数将引发异常。

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4