📜  std :: swap和std :: vector :: swap之间的区别

📅  最后修改于: 2021-05-30 07:56:36             🧑  作者: Mango

std :: swap函数用于交换两个元素,而std :: vector :: swap函数可以交换两个不同矢量容器的所有元素。

以下是std :: swap和std :: vector :: swap之间的一些主要关键区别,

std::swap std::vector::swap
The std::swap() is a built-in function in C++ STL which swaps the value of any two variables passed to it as parameters. The std::vector::swap() function is used to swap the entire contents of one vector with another vector of same type and size.
The std::swap() is comparitively slower than std::vector::swap() function. The std::vector::swap() is comparitively faster than std::swap() function.
If std::swap() function is used for swapping two vectors, it will take O(n) time because it swaps the elements of two vector one by one. The std::vector::swap function is faster than the normal swap function as it swaps the addresses(i.e. the containers exchange references to their data) of two vectors rather than swapping each element one by one which is done in constant time O(1).

程序1 :说明使用std :: swap()交换两个向量。

// CPP program to illustrate swapping 
// of two vectors using std::swap()
  
#include
using namespace std;
  
int main()
{
    vector v1 = {1, 2, 3};
    vector v2 = {4, 5, 6};
      
    // swapping the above two vectors
    // by traversing and swapping each element
    for(int i=0; i<3; i++)
    {
        swap(v1[i], v2[i]);
    }
      
    // print vector v1
    cout<<"Vector v1 = ";
    for(int i=0; i<3; i++)
    {
        cout<
输出:
Vector v1 = 4 5 6 
Vector v2 = 1 2 3

程序2 :说明使用std :: vector :: swap()交换两个向量。

// CPP program to illustrate swapping 
// of two vectors using std::vector::swap()
  
#include
using namespace std;
  
int main()
{
    vector v1 = {1, 2, 3};
    vector v2 = {4, 5, 6};
      
    // swapping the above two vectors
    // using std::vector::swap
    v1.swap(v2);
      
    // print vector v1
    cout<<"Vector v1 = ";
    for(int i=0; i<3; i++)
    {
        cout<
输出:
Vector v1 = 4 5 6 
Vector v2 = 1 2 3
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”