【问题标题】:sorting of map stl in c++; error: not match for operator -在 C++ 中对地图 stl 进行排序;错误:与运算符不匹配 -
【发布时间】:2020-08-04 03:32:22
【问题描述】:

我收到一条错误消息,指出“与运算符不匹配-”。当我使用 sort() 函数时会发生这种情况。

#include <bits/stdc++.h>
using namespace std;

bool comp(pair<char, int> &a, pair<char, int> &b)
{
    return a.first < b.first ? 1 : -1;
}

int main() {
    // your code goes here
    int t;
    cin >> t;
    while (t--)
    {
        string s;
        cin >> s;
        map<char, int> m;
        for(int i = 0; i < s.size(); i++)
        {
            m[s[i]]++;
            cout << (char)s[i];
        }
        cout << "hello";
        sort(m.begin(), m.end(), comp);
    }
    return 0;
}

【问题讨论】:

标签: c++ dictionary stl


【解决方案1】:

std::sort() 想要随机访问迭代器,但 std::map 迭代器不是随机访问的,所以你不能在 std::map 上调用 std::sort(),因为它们没有实现 operator-

std::map 是一个排序容器,按其键排序。而且由于您的密钥很简单char,因此它们已经可以按原样进行比较。

自定义排序std::map正确方法是:

  1. 直接在map 声明中提供比较器,例如:
#include <bits/stdc++.h>
using namespace std;

struct comp {
    bool operator()(const char &a, const char &b) const {
        return a < b; // or whatever you want...
    }
};

int main() {
    // your code goes here
    int t;
    cin >> t;
    while (t--) {
        string s;
        cin >> s;
        map<char, int, comp> m;
        for(int i = 0; i < s.size(); i++) {
            m[s[i]]++;
            cout << s[i];
        }
        cout << "hello";
    }
    return 0;
}
  1. 为密钥类型提供operator&lt;。您不能为基本类型重载运算符,但可以为自定义类型重载:
#include <bits/stdc++.h>
using namespace std;

struct my_key {
    char value;
    my_key(char ch) : value(ch) {}
    bool operator<(const char &rhs) const {
        return value < rhs.value; // or whatever you want...
    }
};

int main() {
    // your code goes here
    int t;
    cin >> t;
    while (t--) {
        string s;
        cin >> s;
        map<my_key, int> m;
        for(int i = 0; i < s.size(); i++) {
            m[s[i]]++;
            cout << s[i];
        }
        cout << "hello";
    }
    return 0;
}

【讨论】:

  • @JeJo 可能有,但这是次要的,与手头的问题并不真正相关。
猜你喜欢
  • 1970-01-01
  • 2016-03-18
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多