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. |
If std::swap() function is used for swapping two vectors A and B, it will call specialized std::swap algorithm for std::vector which in turn calls A.swap(B) and swaps the contents. | The std::vector::swap function exchanges the contents of one vector with another. 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). |
The overloads of std::swap for container adaptors were introduced in C++11. Prior versions of C++ will require linear time complexity to swap vectors | The std::vector::swap function will always swap the contents of vector in constant time. |
实际上,这两个函数将在 O(1) 时间内交换向量的内容并提供相同的性能。为了一致性,使用 std::swap 可能更好。
程序 1 :说明使用 std::swap() 交换两个向量。
CPP
// 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 << v1[i] << " ";
}
// print vector v2
cout << "\nVector v2 = ";
for (int i = 0; i < 3; i++) {
cout << v2[i] << " ";
}
return 0;
}
CPP
// 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 << v1[i] << " ";
}
// print vector v2
cout << "\nVector v2 = ";
for (int i = 0; i < 3; i++) {
cout << v2[i] << " ";
}
return 0;
}
输出:
Vector v1 = 4 5 6
Vector v2 = 1 2 3
程序 2 :说明使用 std::vector::swap() 交换两个向量。
CPP
// 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 << v1[i] << " ";
}
// print vector v2
cout << "\nVector v2 = ";
for (int i = 0; i < 3; i++) {
cout << v2[i] << " ";
}
return 0;
}
输出:
Vector v1 = 4 5 6
Vector v2 = 1 2 3
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程。