[C++] 如何对列表(vector),字典(map)等进行排序

对列表(vector)进行排序

C++中可以使用std::sort()函数对vector进行排序。

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> nums = {4, 2, 8, 6, 5, 3, 1, 7};
    
    // 对vector进行升序排序
    std::sort(nums.begin(), nums.end());
    
    // 输出排序后的vector
    for (int num : nums) {
        std::cout << num << " ";
    }
    
    return 0;
}

输出:

1 2 3 4 5 6 7 8

如果要对vector进行降序排序,可以使用std::greater<int>作为sort()函数的第三个参数。

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> nums = { 4, 2, 8, 6, 5, 3, 1, 7 };

    // 对vector进行降序排序
    std::sort(nums.begin(), nums.end(), std::greater<int>());
    // 或者
    //std::sort(nums.rbegin(), nums.rend());

    // 输出排序后的vector
    for (int num : nums) {
        std::cout << num << " ";
    }

    return 0;
}

输出:

8 7 6 5 4 3 2 1

对字典(map)进行排序

在C++中,map是按照键值对的键进行排序的,因此不需要专门对map进行排序操作。如果你想按照键或值的顺序遍历map,可以直接使用迭代器进行遍历操作。

如果你想按照键的顺序遍历map,可以使用map的默认迭代器,因为map的键是按照升序排序的。

#include <iostream>
#include <map>

int main() {
    std::map<std::string, int> scores = { {"Bob", 78} ,{"Alice", 95}, {"Charlie", 82}, {"Dave", 90} };

    // 按照键的顺序遍历map
    for (auto it = scores.begin(); it != scores.end(); ++it) {
        std::cout << it->first << ": " << it->second << std::endl;
    }

    return 0;
}

输出:

Alice: 95
Bob: 78
Charlie: 82
Dave: 90

如果你想按照值的顺序遍历map,可以使用自定义比较函数,并将map中的键值对存储到vector中,然后对vector进行排序。

#include <iostream>
#include <map>
#include <vector>
#include <algorithm>

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

int main() {
    std::map<std::string, int> scores = {{"Alice", 95}, {"Bob", 78}, {"Charlie", 82}, {"Dave", 90}};
    
    // 将map中的键值对存储到vector中
    std::vector<std::pair<std::string, int>> sortedScores(scores.begin(), scores.end());
    
    // 根据值排序vector
    std::sort(sortedScores.begin(), sortedScores.end(), compare);
    
    // 按照值的顺序遍历vector
    for (const auto& score : sortedScores) {
        std::cout << score.first << ": " << score.second << std::endl;
    }
    
    return 0;
}

输出:

Bob: 78
Charlie: 82
Dave: 90
Alice: 95

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老狼IT工作室

你的鼓励将是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值