c++中map stl的排序;错误:与运算符不匹配 -

0 c++ dictionary stl

我收到一条错误消息,指出“不匹配运算符-”。当我使用 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;
}
Run Code Online (Sandbox Code Playgroud)

图片

图片

Rem*_*eau 6

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

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

自定义排序 a的正确方法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;
}
Run Code Online (Sandbox Code Playgroud)
  1. operator<密钥类型提供一个。您不能为基本类型重载运算符,但可以为自定义类型重载:
#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;
}
Run Code Online (Sandbox Code Playgroud)