对列表(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());// 输出排序后的vectorfor (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());// 输出排序后的vectorfor (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} };// 按照键的顺序遍历mapfor (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());// 根据值排序vectorstd::sort(sortedScores.begin(), sortedScores.end(), compare);// 按照值的顺序遍历vectorfor (const auto& score : sortedScores) {std::cout << score.first << ": " << score.second << std::endl;}return 0;
}
输出:
Bob: 78
Charlie: 82
Dave: 90
Alice: 95