C++映射以有序形式存储键(请注意,它在内部使用自平衡二进制搜索树)。排序是在内部使用运算符“ <”完成的,因此,如果我们使用自己的数据类型作为键,则必须为该数据类型重载此运算符。
让我们考虑有关键数据类型作为结构和映射值作为整数的映射。
// key's structure
struct key
{
int a;
};
// CPP program to demonstrate how a map can
// be used to have a user defined data type
// as key.
#include
using namespace std;
struct Test {
int id;
};
// We compare Test objects by their ids.
bool operator<(const Test& t1, const Test& t2)
{
return (t1.id < t2.id);
}
// Driver code
int main()
{
Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 };
// Inserting above four objects in an empty map
map mp;
mp[t1] = 1;
mp[t2] = 2;
mp[t3] = 3;
mp[t4] = 4;
// Printing Test objects in sorted order
for (auto x : mp)
cout << x.first.id << " " << x.second << endl;
return 0;
}
输出:
101 3
102 2
110 1
115 4
我们还可以使<运算符成为结构/类的成员。
// With < operator defined as member method.
#include
using namespace std;
struct Test {
int id;
// We compare Test objects by their ids.
bool operator<(const Test& t) const
{
return (this->id < t.id);
}
};
// Driver code
int main()
{
Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 };
// Inserting above four objects in an empty map
map mp;
mp[t1] = 1;
mp[t2] = 2;
mp[t3] = 3;
mp[t4] = 4;
// Printing Test objects in sorted order
for (auto x : mp)
cout << x.first.id << " " << x.second << endl;
return 0;
}
输出:
101 3
102 2
110 1
115 4
如果我们不重载<运算符,会发生什么?
如果尝试在地图中插入任何内容,则会出现编译器错误。
#include
using namespace std;
struct Test {
int id;
};
// Driver code
int main()
{
map mp;
Test t1 = {10};
mp[t1] = 10;
return 0;
}
输出:
/usr/include/c++/5/bits/stl_function.h:387:20: error: no match for 'operator<' (operand types are 'const Test' and 'const Test')
{ return __x < __y; }
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。