如何更改配对(>和<)运算符行为?

How to change pair (> and <) operators behavior?

本文关键字:运算符 lt 何更改 gt      更新时间:2023-10-16

我正在尝试对vector< pair<int,char> >进行排序,但我想更改对类型的比较运算符的行为,这样,如果第一个值相等,并且它与(>)运算符进行比较,我希望它将第二个值与(<)运算符进行比较。

我尝试这样做是为了解决uva上的"什么是密码分析?"问题。这是我的方法:

string toLower(string in){
    string out;
    for(int i=0;i<in.length();i++){
        if(in.at(i)<='Z' && in.at(i)>='A'){
            out+=in.at(i)+('a'-'A');
        }
        else if(in.at(i)<='z' && in.at(i)>='a'){
            out+=in.at(i);
        }
    }
    return out;
}

int main(){
    //freopen("in.txt","r",stdin);
    //freopen("tmp.txt","w",stdout);
    vector< pair<int,char> >vp;
    pair<int,char> tp;
    for(char a='a';a<='z';a++){//buliding a table of values and chars
        tp= make_pair(0,a);
        vp.push_back(tp);
    }
    int T;
    cin >> T;
    string s;
    cin.ignore();
    for(int i=0;i<T;i++){
        getline(cin,s);
        s=toLower(s);//remove special chars and convert all to lower
        int l=s.length();
        for(int j=0;j<l;j++){
            vp[s[j]-'a'].first+=1;//increasing the value of each char found
        }
    }
    sort(vp.begin(),vp.end());//ascending sort
    for(int j=25;j>=0;j--){
        cout << (char)(vp[j].second -('a'-'A')) << " " <<vp[j].first << endl;//cout the Capital char and its value backwards (Descending)
    }
    //system("pause");
    return 0;
}

但这就是输出的样子:

S 7
T 6
I 5
E 4
O 3
W 2
U 2
N 2
H 2
A 2
Y 1
Q 1
M 1
C 1
Z 0
X 0
V 0
R 0
P 0
L 0
K 0
J 0
G 0
F 0
D 0
B 0

例如,我希望W U N H AA H N U W

我在其他问题中读过关于重载的文章,但我不知道在这里实现它

这是通过向sort传递自定义比较器函数来完成的。你可以用这样的lambda最容易地做到这一点:

sort(
    vp.begin(),
    vp.end(),
    [](const pair<int,char>& lhs, const pair<int,char>& rhs) -> bool {
        return lhs.first != rhs.first 
            ? lhs.first < rhs.first 
            : lhs.second < rhs.second;
    }
);

这段代码先按升序first排序,然后按升序second排序,但您可以调整两个比较的优先级和方向,以按您想要的方式排序。

只需提供自己的比较功能:

bool comp(const std::pair<int, char>& a, const std::pair<int, char>& b)
{
  if (a.first > b.first) {
    return true;
  } else if (a.first == b.first && a.second < b.second) {
    return true;
  }
  return false;
}

然后在排序时使用它:

sort(vp.begin(),vp.end(), comp);

我正在尝试对向量<pair>但我想更改比较的行为

只需定义一个合适的二进制谓词函数,并将其作为第三个参数传递给std::sort。请记住,它应该实现严格的弱排序:

bool foo(const pair<int,char>& lhs, const pair<int,char>& rhs)
{
  // implement logic here
}
....
sort(vp.begin(),vp.end(), foo);