C++字符串数字的比较
来源:互联网 发布:union软件安卓 编辑:程序博客网 时间:2024/04/20 20:05
假设:
有这么一个字符串集合,"1","2","3",........."10000000", "40","20".
要求进行排序。
基本想法: 把字符串转化为数字,进行对比。
但是有一个问题:也许这个字符串的长度超过了 普通整数的范围了,怎么办? 有人说用 long long ,可以,但不优雅,而且无法对更加大的数字进行排序。
解决方法: 使用大数的思想。代码如下;
#include <iostream>#include <functional>#include <map>#include <string>#include <vector>#include <iterator>#include <algorithm>#include <utility>#include <cassert>using namespace std;struct string_Intnumber_checker{ bool operator()(const string& str) const{ if(!str.empty()) { if(string::npos == str.find_first_not_of("0123456789")) { return true; } } return false; }};struct string_Intnumber_cmp{ bool operator()(const string& x, const string& y) const{ string_Intnumber_checker checker; assert(checker(x)); assert(checker(y)); if(x.length() > y.length()) { return false; } else if(x.length() == y.length()) { int len = x.length() - 1; while(x[len] == y[len] && x.length() >= 0) len--; if(len >= 0 && x[len] > y[len]) return false; else return true; } else { return true; } } };int main(){ vector<string> strVec = {"111111119999999999800008888888888888888888","1", "9", "20", "7", "40"}; sort(strVec.begin(), strVec.end(), string_Intnumber_cmp()); copy(strVec.begin(), strVec.end(), ostream_iterator<string>(cout,"\n"));}
结果如下:
1
7
9
20
40
111111119999999999800008888888888888888888
0 0
- 数字与字符串的比较
- C++字符串数字的比较
- shell 中的数字和字符串的比较
- javaScript字符串与数字之间的比较
- linux c/c++ IP字符串转换成可比较大小的数字
- 数字和字符串比较
- c的数字与字符串的转化
- C语言“字符串-数字”之间的转换
- C语言 数字和字符串的转换
- C C++ 数字与字符串的转化
- C语言 数字转字符串的函数
- C 字符串与数字的转换
- c计算数字字符串的和
- 【Hibernate】字符串形式的数字如何正确的比较大小
- js字符串类型的数字比较的大小
- oracle中字符串的大小比较,字符串与数字的比较和运算
- java数字字符串比较大小
- shell数字和字符串比较
- 把任意Drawable转换成基于progress填充的drawable
- 仿微信页面切换图标颜色渐变效果
- canvas实现简单的Amaziograph效果画对称图
- sqlite3:not found 解决方法
- RecyclerView 中的 item 如何居中问题
- C++字符串数字的比较
- android5.0使用Notification报RemoteServiceException的解决办法
- java-基本数据类型 循环
- 可设置圆角背景边框的按钮, 通过调节色彩明度自动计算按下(pressed)状态颜色
- 左中右结构的行布局
- which命令
- PhotoView点击放大图片效果
- MVC、MVP、MVVM的区别
- 让任意view具有滑动效果的SlideUp