作为用户定义数据类型的具有密钥的C++映射

C++映射 以有序的形式存储密钥(请注意,它在内部使用自平衡二进制搜索树)。排序是使用运算符“

null

让我们考虑一下 地图 以键数据类型为结构,映射值为整数。

// 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 <bits/stdc++.h>
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<Test, int > 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 <bits/stdc++.h>
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<Test, int > 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 <bits/stdc++.h>
using namespace std;
struct Test {
int id;
};
// Driver code
int main()
{
map<Test, int > 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; }

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享