STL中的mapset默认时不支持存结构体的,如果要添加结构体的支持,必须手动重载<运算符。

原因:map和set底层都是通过红黑树实现的,红黑树搜索树的一种,插入数据时要比较大小,所以结构体必须重载小于号

示例:

#include <iostream>
#include <string>
#include <set>

using namespace std;

typedef struct stu_st {
    string name;
    int age;
}stu_t;

int main() {
    set<stu_t> stu_infos;

    stu_t a, b;
    a.name = "xiaoming";
    a.age = 20;

    b.name = "xiaohua";
    b.age = 21;

    stu_infos.insert(a);
    stu_infos.insert(b);

    cout << stu_infos.size() << endl;

    return 0;
}

以上代码在vs下编译报错:

问题很明确,没有重载<符号,添加上以下代码即可:

bool operator<(const stu_t& a, const stu_t& b) {
    return a.name < b.name;
}
最后修改:2019 年 04 月 21 日
如果觉得我的文章对你有用,请随意赞赏