C++ 对string字符串排序

只能说c++的sort()真的很神奇:
对string类型数据进行字符串内排序,例如:
输入:dcba
输出:abcd
代码:

    string str;
    while(cin>>str){
        int len = str.length();
        sort(str.begin(), str.end());
        cout<<str<<endl;
    }
  • 14
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++中,标准库并没有提供直接支持不等长字符串排序的函数,因为C++的`std::string`类型默认是等长的,即所有的字符数组都有相同的长度。如果你需要对不等长字符串进行排序,通常会用到自定义比较函数或者使用一些第三方库,如`boost`中的`multi_index_container`。 一个常见的做法是定义一个结构体或类,其中包含一个字符串和其长度,然后使用这个复合类型的容器来进行排序。这里是一个简单的例子: ```cpp #include <string> #include <vector> #include <algorithm> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/hashed_index.hpp> // 定义一个结构体,包含字符串和长度 struct StringWithLength { std::string str; size_t length; }; // 自定义比较函数,用于按长度排序 bool compareStringLength(const StringWithLength& a, const StringWithLength& b) { return a.length < b.length; } int main() { std::vector<StringWithLength> strings = {/*你的字符串列表*/}; // 使用boost的multi_index_container进行排序 boost::multi_index_container<StringWithLength, boost::multi_index::indexed_by<boost::multi_index::ordered_unique<boost::multi_index::member<StringWithLength, size_t, &StringWithLength::length>>, boost::multi_index::hashed_unique<boost::multi_index::tag<>, boost::multi_index::member<StringWithLength, std::string const&, &StringWithLength::str>>>> my_string_list(strings); std::sort(my_string_list.begin(), my_string_list.end(), compareStringLength); // 现在我的_string_list已经是按长度升序排列的了 for (const auto& str : my_string_list) { std::cout << str.str << " (" << str.length << ")\n"; } return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值