在其他语言(如C++)中如何实现字典序排序?
时间: 2024-11-03 10:23:10 浏览: 48
在C++中,你可以使用标准库中的`std::sort`函数或者自定义比较函数来实现字典序排序。这里提供一个简单的例子:
```cpp
#include <algorithm>
#include <string>
// 自定义比较函数
bool compare(const std::string& a, const std::string& b) {
if (a.size() != b.size()) return a.size() < b.size(); // 如果长度不同按长度升序
for (size_t i = 0; i < a.size(); ++i)
if (a[i] != b[i]) return a[i] < b[i]; // 否则逐个字符比较
return false; // 如果完全相同返回false,保持原有的顺序
}
int main() {
std::vector<std::string> words = {"apple", "apricot", "banana", "cherry"};
std::sort(words.begin(), words.end(), compare);
for (const auto& word : words) {
std::cout << word << " ";
}
return 0;
}
```
在这个例子中,我们创建了一个名为`compare`的函数,它接受两个字符串并按字典序进行比较。然后将这个函数传递给`std::sort`,对`words`容器中的元素进行排序。
阅读全文
相关推荐


















