[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

猜你喜欢

转载自blog.csdn.net/u011775793/article/details/136279835