std :: unordered_map :: swap()是C++ STL中的内置函数,可将容器的元素交换到另一个容器。调用此函数后,调用者unordered_map的元素将成为被称为unordered_map的元素,而被调用unordered_map的元素将成为调用者unordered_map的元素。
内部元素交换未完成,仅更改了两个unordered_map的引用类型。
句法
unordered_map.swap ( unordered_map& ump )
返回类型:此函数的返回类型无效。
参数:另一个具有相同元素类型的unordered_map。
复杂度:其复杂度是恒定的。
例子1
// C++ code to illustrate the method
// unordered_map swap
#include
using namespace std;
int main()
{
unordered_map sample1, sample2;
// Map initialization
sample1 = { { 2, 2 }, { 3, 4 }, { 4, 6 }, { 5, 8 } };
sample2 = { { 10, 11 }, { 12, 13 }, { 14, 15 }, { 26, 17 } };
// printing details before calling swap
cout << " Elements of maps before swap \n";
cout << " Elements of first map are : \n";
for (auto& x : sample1)
cout << x.first << " : " << x.second << endl;
cout << " Elements of second map are : \n";
for (auto& x : sample2)
cout << x.first << " : " << x.second << endl;
// swapping
sample1.swap(sample2);
cout << " Elements of maps after swap \n";
cout << " Elements of first map are : \n";
for (auto& x : sample1)
cout << x.first << " : " << x.second << endl;
cout << " Elements of second map are : \n";
for (auto& x : sample2)
cout << x.first << " : " << x.second << endl;
return 0;
}
输出:
Elements of maps before swap
Elements of first map are :
5 : 8
4 : 6
3 : 4
2 : 2
Elements of second map are :
14 : 15
26 : 17
12 : 13
10 : 11
Elements of maps after swap
Elements of first map are :
14 : 15
26 : 17
12 : 13
10 : 11
Elements of second map are :
5 : 8
4 : 6
3 : 4
2 : 2
例子2
// C++ code to illustrate the method
// unordered_map swap
#include
using namespace std;
int main()
{
unordered_map sample1, sample2;
// Map initialization
sample1 = { { 'a', 2 }, { 'b', 4 }, { 'c', 6 }, { 'd', 8 } };
sample2 = { { 'e', 11 }, { 'f', 13 }, { 'h', 15 } };
// printing details before calling swap
cout << " Elements of maps before swap \n";
cout << " Elements of first map are : \n";
for (auto& x : sample1)
cout << x.first << " : " << x.second << endl;
cout << " Elements of second map are : \n";
for (auto& x : sample2)
cout << x.first << " : " << x.second << endl;
// swapping
sample1.swap(sample2);
cout << " Elements of maps after swap \n";
cout << " Elements of first map are : \n";
for (auto& x : sample1)
cout << x.first << " : " << x.second << endl;
cout << " Elements of second map are : \n";
for (auto& x : sample2)
cout << x.first << " : " << x.second << endl;
return 0;
}
输出:
Elements of maps before swap
Elements of first map are :
d : 8
c : 6
b : 4
a : 2
Elements of second map are :
h : 15
f : 13
e : 11
Elements of maps after swap
Elements of first map are :
h : 15
f : 13
e : 11
Elements of second map are :
d : 8
c : 6
b : 4
a : 2
注意:调用方和被调用的unordered_map都应包含相同类型的元素,否则我们将得到编译时错误。
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。