温馨提示×

C++ sort()怎样处理字符串

c++
小樊
128
2024-07-18 14:48:17
栏目: 编程语言

在C++中,可以使用std::sort()函数对字符串进行排序。排序字符串时,可以使用std::sort()函数的第三个参数来指定比较函数,用于指定排序规则。

以下是一个示例代码,演示如何使用std::sort()对字符串进行排序:

#include <iostream>
#include <algorithm>
#include <string>

bool myComparator(const std::string& s1, const std::string& s2) {
    return s1 < s2;
}

int main() {
    std::string str = "hello world";
    std::sort(str.begin(), str.end());
    
    std::cout << "Sorted string: " << str << std::endl;
    
    std::string str2 = "acbdef";
    std::sort(str2.begin(), str2.end(), myComparator);
    
    std::cout << "Sorted string with custom comparator: " << str2 << std::endl;
    
    return 0;
}

在上面的示例中,首先对字符串"hello world"进行排序,然后对字符串"acbdef"进行排序,并使用自定义比较函数myComparator指定排序规则。最终输出排序后的字符串。

0