C++实现01串排序

摘要:
主题内容:首先按长度对01个字符串进行排序。如果长度相同,则按数字1从少到多排序。如果1的数字相同,请按ASCII代码值对它们进行排序。输入描述:输入数据包含一些01个字符串,01个字符串的长度不超过256个字符。输出描述:重新排列01个字符串的顺序,以便根据主题描述对字符串进行排序。

题目内容:将01串首先按长度排序,长度相同时,按1的个数从少到多进行排序,1的个数相同时再按ASCII码值排序。

输入描述:输入数据中含有一些01串,01串的长度不大于256个字符。

输出描述:重新排列01串的顺序,使得串按题目描述的方式排序。

题目分析:

(1)定义一个多重集合容器,该容器的元素类型为string,采用设定的比较函数

(2)因为元素是string而非结构体,所以可以编写比较函数,重载“()”操作符。对于参与比较的每两个字符串,若他们长度不同,则按长度由小到大返回;若他们长度相同,则计算每个字符串中‘1’的个数,若‘1’的个数不同,则按‘1’的个数从少到多返回;若‘1’的个数相同,则按ASCII码值,即字符串的大小从小到大返回。

参考代码:

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

using namespace std;

struct Comp
{
    bool operator()(const string &s1,const string &s2)
    {
         if(s1.length()!=s2.length()) return s1.length()<s2.length();
         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[])
{
    multiset<string,Comp> ms;
    string s;
    while(cin>>s)
    {
        ms.insert(s);
        if(cin.get()=='
')
        {
            break;
        }
    }
    for(multiset<string,Comp>::iterator it=ms.begin();it!=ms.end();it++)
    {
        cout<<*it<<endl;
    }
    system("pause");
    return 0;
}

运行结果:

C++实现01串排序第1张

免责声明:文章转载自《C++实现01串排序》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇(5) openssl speed(测试算法性能)和openssl rand(生成随机数)如何申请Pycharm学生免费激活码下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

SortedList、SortedSet、HashSet、Hashtable、Dictionary、SortedDictionary 排序/可重复排序/过滤重复排序等简单对比

//泛型的键值集合/有序/Hash算法/占内存较大/不排序,不受装填因子的限制,对读写操作效率较高 Dictionary<int, string> dc = new Dictionary<int, string>(); dc.Add(1, "111111");...

Java中InputStream输入流转String字符串的操作

目录 一、InputStream类中read方法 二、开源工具类IOUtils中toString方法 三、开源工具类CharStreams中toString方法 一、InputStream类中read方法 package com.zhiyin.test; import java.io.InputStream; public class MyT...

操作笔记:linux下安装mysql

1,检查linux下是否安装了mysql shell指令如下: [root@iZ945sgm0ugZ ~]# rpm -qa|grep -i mysql 如果有的话:做出挨个删除(eg:rpm -ev mysql-connector-odbc-5.2.5-6.el7.x86_64) [root@iZ945sgm0ugZ ~]# rpm -qa|grep -...

httpclient 实现文件上传中转

开发功能: web前端提交上传文件 —> a服务器接收 —> 转发到b服务器进行文件处理 下面是简单实现的代码,具体细节优化根本自己的需求更改。 public String handleResponse(HttpServletRequest request, HttpServletResponse response)...

C# HttpWebRequest请求服务器(Get/Post兼容)

简单示例说明 public static string HttpGet(string url, string data,string Method, int timeOut, Encoding encode, string contentType = "application/x-www-form-urlencoded", CookieContainer...

java 正则表达式

java 正则表达式 package com.project.utils; import org.apache.commons.lang.StringUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ContentUtils {...