当使用std::sort
对容器中的元素进行排序时,您需要提供三个参数:
- 起始迭代器:指向要排序的范围的起始位置的迭代器。
- 结束迭代器:指向要排序的范围的结束位置的下一个迭代器。
- 比较函数(可选):用于定义排序顺序的比较函数或lambda表达式。
例如,在我们的示例中,我们使用std::sort
对countVector
进行排序,其中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;
}