为什么我的超载不是<运算符不适用于STL排序 [英] Why isn't my overloading < operator not working for STL sort

查看:52
本文介绍了为什么我的超载不是<运算符不适用于STL排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码,我想根据字符串的最后一个字符对字符串向量进行排序.我已经完成了以下操作,但排序是默认规则完成的.

I have this following code where I want to sort vector of string according to the last character of the string. I've done the following but the sorting is done by default rules.

这是超载<部分:

Here's the overloading < part:

bool operator<(const string &s1, const string &s2){
    return s1.at(s1.size() - 1) < s2.at(s2.size() - 1);
}

这是主要内容:

vector <string> nameList;
int n;
cin>>n;
while(n--){
    string name;
    char str[100];
    cin>>str;
    name += str;
    nameList.push_back(name);
}

sort(nameList.begin(), nameList.end());
for(int i = 0; i < nameList.size(); i++)
    cout<<nameList.at(i)<<endl;

ideone中的代码: LINK

Code in ideone: LINK

推荐答案

如前所述,您的operator<没有被调用,std::stringstd名称空间中已经有重载的运算符.

As noted, your operator< is not being called, std::string already has overloaded operators in the std namespace.

std::sort 有两个版本,一个将使用operator<和另一个使用自定义谓词对容器进行排序的对象. 添加自定义谓词,您仍然可以根据需要使用sortvector进行排序;

There are two versions of std::sort, one that will use operator< and another that takes a custom predicate to sort the container. Add a custom predicate, you can still used sort to sort your vector as required;

#include <algorithm>
#include <string>
#include <iostream>
#include <vector>
using namespace std;

bool lastchar(const string &s1, const string &s2){
    return s1.at(s1.size() - 1) < s2.at(s2.size() - 1);
}

int main(){
        vector <string> nameList;
        int n;
        cin>>n;
        while(n--){
            string name;
            char str[100];
            cin>>str;
            name += str;
            nameList.push_back(name);
        }

        sort(nameList.begin(), nameList.end(), &lastchar);
        for(int i = 0; i < nameList.size(); i++)
            cout<<endl<<nameList.at(i);

        return 0;
}

我将其称为lastchar,但您可以将其命名为最好的.另外,如果您可以使用C ++ 11或更高版本,则可以使谓词为lambda.

I've called it lastchar, but you can name it what ever is best. As an added bonus, if you can used C++11 or above, you can make the predicate a lambda.

sort(nameList.begin(), nameList.end(), [] (const string &s1, const string &s2){
  return s1.at(s1.size() - 1) < s2.at(s2.size() - 1);
});

这篇关于为什么我的超载不是&lt;运算符不适用于STL排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆