最近在用 map 和 set ,两个一起使用,set 作为 map 的 value。突然发现要获取 set 里的元素有点曲折啊,记录一下,方便以后随时查看。 我们知道 set 和 map 底层实现都是二叉树,自定义类型必须重载一个小于号运算符。
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <set>
enum label_type
{
LABEL_TYPE_ONE,
LABEL_TYPE_TWO,
LABEL_TYPE_THREE
};
struct label_map
{
int label;
enum label_type type;
};
bool operator<(const struct label_map& lhs, const struct label_map& rhs)
{
return lhs.label < rhs.label;
}
std::map<int, std::set<struct label_map>> map_set;
void getSetOfMap(int key, std::set<struct label_map> &label)
{
auto it = map_set.find(key);
if(it != map_set.end())
{
label = map_set[key];
}
}
void getSetElement(int key, struct label_map *label)
{
std::set<struct label_map> st;
getSetOfMap(key, st);
auto it = st.begin();
*label = *it;
}
int main()
{
struct label_map label_1 = {1001, LABEL_TYPE_ONE};
struct