Map是STL中的容器,用於以鍵值對的形式存儲元素。在內部,映射中的元素始終按其鍵排序。Map主要實現為二進製搜索樹。
map::at()
at()函數用於將引用返回給與鍵k關聯的元素。
用法:
map1.at(k) 參數: k is the Key value of the element whose associated value is accessed.
返回:它返回對鍵值等於k的元素的關聯值的引用。
例子:
Input: map1 = { {1, 'a'}, {2, 'b'}, {3, 'c'}, {4, 'd'} } map1.at(2); Output:b Input: map2 = { {'w', 1}, {'x', 2}, {'y', 3} } map2.at('w'); Output:1
// CPP program to illustrate
// Implementation of swap() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Take any two maps
map<int, char> map1;
map<char, int> map2;
map1[1] = 'a';
map1[2] = 'b';
map1[3] = 'c';
map1[4] = 'd';
map2['w'] = 1;
map2['y'] = 2;
map2['z'] = 3;
// Print the associated element
cout << "Element at map1[2] = "
<< map1.at(2) << endl;
cout << "Element at map2['w'] = "
<< map2.at('w') << endl;
return 0;
}
輸出:
Element at map1[2] = b Element at map2['w'] = 1
map::swap()
swap()函數用於交換兩個Map的內容,但是Map的類型必須相同,盡管大小可能會有所不同。句法:
map1.swap(map2) OR swap(map1, map2) 參數: map1 is the first map object. map2 is the second map object.
返回值:沒有
例子:
Input:map1 = { {1, 'a'}, {2, 'b'}, {3, 'c'}, {4, 'd'} } map2 = { {5, 'w'}, {6, 'x'}, {7, 'y'} } swap(map1, map2) Output:map1 = { {5, 'w'}, {6, 'x'}, {7, 'y'} } map2 = { {1, 'a'}, {2, 'b'}, {3, 'c'}, {4, 'd'} }
// CPP program to illustrate
// Implementation of swap() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Take any two maps
map<int, char> map1, map2;
map1[1] = 'a';
map1[2] = 'b';
map1[3] = 'c';
map1[4] = 'd';
map2[5] = 'w';
map2[6] = 'x';
map2[7] = 'y';
// Swap elements of queues
swap(map1, map2);
// Print the elements of maps
cout << "map1:\n"
<< "\tKEY\tELEMENT\n";
for (auto it = map1.begin();
it != map1.end(); it++)
cout << "\t" << it->first << "\t" << it->second << '\n';
cout << "map2:\n"
<< "\tKEY\tELEMENT\n";
for (auto it = map2.begin();
it != map2.end(); it++)
cout << "\t" << it->first << "\t" << it->second << '\n';
return 0;
}
輸出:
map1: KEY ELEMENT 5 w 6 x 7 y map2: KEY ELEMENT 1 a 2 b 3 c 4 d
相關用法
注:本文由純淨天空篩選整理自AKASH GUPTA 6大神的英文原創作品 map::at() and map::swap() in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。