映射是STL中的容器,用于以键值对的形式存储元素。在内部,映射中的元素始终按其键排序。地图主要实现为二叉搜索树。
映射:: at()
at()函数用于返回对与键k关联的元素的引用。
句法:
map1.at(k)
Parameters:
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
using namespace std;
int main()
{
// Take any two maps
map map1;
map 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()函数用于交换两个地图的内容,但是地图的类型必须相同,尽管大小可能会有所不同。
句法:
map1.swap(map2)
OR
swap(map1, map2)
Parameters:
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
using namespace std;
int main()
{
// Take any two maps
map 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
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。