对结构体vector进行sort(C++)

1 篇文章 0 订阅
1 篇文章 0 订阅

自己写一个小程序时,自己定了一个结构体word,并使用了C++标准库中的vector来作为结构体word的容器。我在程序需要对所有的word进行排序。于是,问题来了:如何对结构体vector,使用标准库中vector封装好sort()来排序呢

两种方法

1. 运算符的重构

这是我定义的word(token:中文单词,lenPro:拼音个数(即为字数),Pro:拼音)

typedef struct word
{
    string token;
    int lenPro;
    vector<string> pro;
    bool operator<(const word& rhs) const   //for asc
    {
        return lenPro < rhs.lenPro;
    }
    bool operator>(const word& rhs) const   //for des
    {
        return lenPro > rhs.lenPro;
    }
} word;

如word定义,我们重构了‘>’和‘<’运算符。我们用“<”的重构作为例子说明:

bool operator<(const word& rhs) const   //for asc
{
    return lenPro < rhs.lenPro;
}
//这里我们选择了lenPro属性作为比较的基准

//C++的函数重构格式这里就不说,因为就是一个固定格式,这里就不赘述了。

//主要看“const word& rhs”的参数声明:C++中使用“&”,让函数的参数“成为”调用函数中对应的变量(在函数执行后,参数的改变是有效的,就像在调用函数中使用一下)
//例如:
//#include <iostream>
//#include <string>
//
//using namespace std;
//
//void getString1(string a);
//void getString2(string& a);
//
//int main()
//{
//    string a = "Changed?";
//    cout<<"The source: "<<a<<endl;
//    cout<<"Start"<<endl;
//    getString1(a);
//    cout<<"After getString1: "<<a<<endl;
//    getString2(a);
//    cout<<"After getString2: "<<a<<endl;
//    return 0;
//}
//
//void getString1(string a)
//{
//    a = "Keep Fighting!";
//    return;
//}
//void getString2(string& a)
//{
//    a = "Keep Fighting!";
//    return;
//}

这里写图片描述

如图所示,只有void getString2(string& a)中对a的操作是有效的,也就是a可以看做将“真正的变量a”传给了getString2()。

然后,我们这样使用“include < functional>”头文件中的”less< 结构体名称>()“和”greater< 结构体名称>()“来函数代替重构的“<”和“>”:

void lex::sortByLenAsc()
{
    sort(words.begin(), words.end(), less<word>());
    return;
}

void lex::sortByLenDec()
{
    sort(words.begin(), words.end(), greater<word>());
    return;
}

我们读入数据后,调用函数:

int main()
{
    lex c;
    c.showWords(0, 10);
    cout << endl;

    c.sortByLenAsc();
    c.showWords(0, 10);
    cout << endl;

    c.sortByLenDec();
    c.showWords(0, 10);

    cout << endl << c.getLenWords() << endl;

    return 0;
}

结果如下
这里写图片描述

2. 编写 “bool cmp(const void s1, const void s2);”

bool cmpAsc(const word& s1, const word& s2) //for sort
{
    return s1.lenPro < s2.lenPro;
}

bool cmpDec(const word& s1, const word& s2) //for sort
{
    return s1.lenPro > s2.lenPro;
}

调用基本与前面相同:

void lex::sortByLenAsc()
{
    sort(words.begin(), words.end(), cmpAsc);
    return;
}

void lex::sortByLenDec()
{
    sort(words.begin(), words.end(), cmpDes);
    return;
}

运行结果是相同,这里就不展示了。

至此,我们已经有两种方法来使用vector封装好的sort来对结构体vector进行升序(降序)排序了。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值