按字典顺序对整数进行排序C ++ [英] sort array of integers lexicographically C++
本文介绍了按字典顺序对整数进行排序C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按字典顺序对大整数数组(例如1密耳元素)进行排序.
I want to sort a large array of integers (say 1 millon elements) lexicographically.
示例:
input [] = { 100, 21 , 22 , 99 , 1 , 927 }
sorted[] = { 1 , 100, 21 , 22 , 927, 99 }
我已使用最简单的方法完成了此操作:
I have done it using the simplest possible method:
- 将所有数字转换为字符串(非常昂贵,因为它将占用大量内存)
- 将
std:sort
与strcmp
用作比较功能 - 将字符串转换回整数
- convert all numbers to strings (very costly because it will take huge memory)
- use
std:sort
withstrcmp
as comparison function - convert back the strings to integers
有没有比这更好的方法了?
Is there a better method than this?
推荐答案
将 std::sort()
与合适的比较功能.这样可以减少内存需求.
Use std::sort()
with a suitable comparison function. This cuts down on the memory requirements.
比较功能可以使用n % 10
,n / 10 % 10
,n / 100 % 10
等访问单个数字(对于正整数;负整数的工作方式有所不同).
The comparison function can use n % 10
, n / 10 % 10
, n / 100 % 10
etc. to access the individual digits (for positive integers; negative integers work a bit differently).
这篇关于按字典顺序对整数进行排序C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文