字符串按1的个数排序

01 字符串按1的个数排序输出:

源码:

Code:
  1. #include <iostream>   
  2. #include <fstream>   
  3. #include <string>   
  4. #include <vector>   
  5. #include <algorithm>   
  6.   
  7. using namespace std;   
  8.   
  9. bool cmp(const string &s1,const string &s2)   
  10. {   
  11.     //彻底修改排序规则,只按1的数量排序   
  12.     //若1的数量相等,则按照出现顺序排序   
  13.     //否者,按ASCII排序   
  14.     //只能用“<”或“>"   
  15.     int c1= count(s1.begin(),s1.end(),'1');   
  16.     int c2= count(s2.begin(),s2.end(),'1');   
  17.     return c1!=c2?c1<c2:c1<c2; //Thinking  
  18. }   
  19.   
  20. int main(int argc,char *argv[])   
  21. {   
  22.     ifstream cin("aaa.txt");   
  23.     vector<string>vstr;   
  24.     string str;   
  25.     while(cin>>str)   
  26.     {   
  27.         vstr.push_back(str);   
  28.     }   
  29.     sort(vstr.begin(),vstr.end(),cmp);   
  30.     vector<string>::iterator it;   
  31.     for(it= vstr.begin();it<vstr.end();it++)   
  32.       cout<<*it<<endl;   
  33.     return 0;   
  34. }  

 

结果:

Code:
  1. input: (aaa.txt)   
  2.   
  3. 1001100   
  4. 1111110   
  5. 001   
  6. 110001   
  7. 10101   
  8.   
  9. out put :   
  10.   
  11.  001   
  12. 1001100   
  13. 110001   
  14. 10101   
  15. 1111110   

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值