C++实现按1的个数排序

题目内容:有一些01字符串,将其按1的个数的多少的顺序进行输出。

输入描述:本题只有一组测试数据。输入数据由若干数字组成,它是由若干个01组成的数字。

输出描述:对所有输入的数据,按1的个数进行生序排序,每行输出一个数字。

题目分析:

(1)定义一个string型向量容器存储输入的数据;定义一个string型变量作为向量容器的元素;定义排序方法,若‘1’的个数不相等则按‘1’的个数从小到大的顺序返回,否则按字符串从小到大的顺序返回

(2)从键盘读入字符串,将读入的每个字符串插入向量容器

(3)对向量容器中的元素按照设定的比较函数进行排序

(4)遍历向量容器并输出每一个元素

参考代码:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;
bool myComp(const string &s1,const string &s2)
{
    int c1=count(s1.begin(),s1.end(),'1');
    int c2=count(s2.begin(),s2.end(),'1');
    return c1!=c2?c1<c2:s1<s2;
}
int main(int argc,char * argv[])
{
    vector<string> vstr;
    string str;
    while(cin>>str)
    {
        vstr.push_back(str);
        if(cin.get()=='
')
        {
            break;
        }
    }
    sort(vstr.begin(),vstr.end(),myComp);
    for(vector<string>::iterator it=vstr.begin();it<vstr.end();it++)
        cout<<*it<<endl;
    system("pause");
    return 0;
}

运行结果:

原文地址:https://www.cnblogs.com/cysolo/p/3381437.html