01 字符串按1的个数排序输出:
源码:
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- #include <algorithm>
- using namespace std;
- bool cmp(const string &s1,const string &s2)
- {
- //彻底修改排序规则,只按1的数量排序
- //若1的数量相等,则按照出现顺序排序
- //否者,按ASCII排序
- //只能用“<”或“>"
- int c1= count(s1.begin(),s1.end(),'1');
- int c2= count(s2.begin(),s2.end(),'1');
- return c1!=c2?c1<c2:c1<c2; //Thinking
- }
- int main(int argc,char *argv[])
- {
- ifstream cin("aaa.txt");
- vector<string>vstr;
- string str;
- while(cin>>str)
- {
- vstr.push_back(str);
- }
- sort(vstr.begin(),vstr.end(),cmp);
- vector<string>::iterator it;
- for(it= vstr.begin();it<vstr.end();it++)
- cout<<*it<<endl;
- return 0;
- }
结果:
- input: (aaa.txt)
- 1001100
- 1111110
- 001
- 110001
- 10101
- out put :
- 001
- 1001100
- 110001
- 10101
- 1111110