std::sort()
wants random-access iterators, but std::map
iterators are not random-access, so you can't call std::sort()
on a std::map
, as they don't implement operator-
.
std::map
is a sorted container, sorted on its keys. And since your keys are simple char
, they are already comparable as-is.
The correct way to custom sort a std::map
is to either:
- provide a comparator directly in the
map
declaration, eg:
#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;
}
- Provide an
operator<
for the key type. You can't overload operators for fundamental types, but you can for custom types:
#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;
}