std::sort 原来这样用,std的妙处(示例排序)

当使用std::sort对容器中的元素进行排序时,您需要提供三个参数:

  1. 起始迭代器:指向要排序的范围的起始位置的迭代器。
  2. 结束迭代器:指向要排序的范围的结束位置的下一个迭代器。
  3. 比较函数(可选):用于定义排序顺序的比较函数或lambda表达式。

例如,在我们的示例中,我们使用std::sortcountVector进行排序,其中countVector是一个存储字符计数的std::vector<std::pair<char, int>>容器,因此我们将使用以下方式调用std::sort

std::sort(countVector.begin(), countVector.end(), compare);

在这里,countVector.begin()表示范围的起始位置,countVector.end()表示范围的结束位置的下一个迭代器,而compare是我们自定义的比较函数,用于定义排序顺序。

如果不提供比较函数,则默认情况下std::sort会按升序对元素进行排序。

#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
#include <algorithm>

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

int main() {
    std::string input = "aaddccdc";
    std::unordered_map<char, int> charCount;

    for (char c : input) {
        charCount[c]++;
    }

    std::vector<std::pair<char, int>> countVector(charCount.begin(), charCount.end());
    
    // 使用 std::sort 对 countVector 进行排序
    std::sort(countVector.begin(), countVector.end(), compare);

    for (const auto& pair : countVector) {
        std::cout << pair.first << ": " << pair.second << std::endl;
    }

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值