我们已经讨论了C++ STL中的map和C++ STL中的multimap。这些数据结构的默认行为是按升序存储元素。在地图和多地图中插入元素时如何确保倒序或降序。
这个想法是当map / multimap实例时发挥更大的函数。
地图中的降序:
映射存储键值对。自平衡BST(通常是红黑树)用于实现它。
例子:
Input : (10, "queen"), (20, "rose"), (5," lion")
Output : (20, "rose"), (10, "queen"), (5," lion")
// C++ program makes a map to store
// elements in descending order.
#include
using namespace std;
int main()
{
// Here if greater is used to make
// sure that elements are stored in
// descending order of keys.
map > mymap;
// Inserting the elements one by one
mymap.insert(make_pair(10, "queen"));
mymap.insert(make_pair(20, "rose"));
mymap.insert(make_pair(5," lion"));
// begin() returns to the first value of map.
map :: iterator it;
for (it=mymap.begin() ; it!=mymap.end() ; it++)
cout << "(" << (*it).first << ", "
<< (*it).second << ")" << endl;
return 0;
}
输出:
(20, rose)
(10, queen)
(5, lion)
多图的降序:
Multimap与map相似,只是多个元素可以具有相同的键。在这种情况下,键值和映射值对必须是唯一的,而不是每个元素都是唯一的。
Input : (10, "queen"), (20, "rose"), (5," lion"),
(20, "van"), (20, "watch"), (5, "joker")
Output : (20, rose), (20, van), (20, watch),
(10, queen), (5, lion), (5, joker)
// C++ program makes a multimap to store
// elements in descending order.
#include
using namespace std;
int main()
{
// Here if greater is used to make
// sure that elements are stored in
// descending order of keys.
multimap > mymap;
// Inserting the elements one by one
mymap.insert(make_pair(10, "queen"));
mymap.insert(make_pair(20, "rose"));
mymap.insert(make_pair(5," lion"));
mymap.insert(make_pair(20, "van")); // Duplicates allowed
mymap.insert(make_pair(20, "watch"));
mymap.insert(make_pair(5,"joker"));
// begin() returns to the first value of multimap.
multimap :: iterator it;
for (it=mymap.begin() ; it!=mymap.end() ; it++)
cout << "(" << (*it).first << ", "
<< (*it).second << ")" << endl;
return 0;
}
输出:
(20, rose)
(20, van)
(20, watch)
(10, queen)
(5, lion)
(5, joker)
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。