c++排序:具有相同数组值的排序列表
c++ sort: ranking list with same value of an array
我试图显示我的数组qt的排名列表,其中包含5个数字。
int i, j;
int qt[5] = {10,20,10,50,20};
int tempqt;
for (i=0; i<5; i++)
{
for(j=(i+1); j<5; j++)
{
if (qt[i] >= qt[j])
{
tempqt = qt[i];
qt[i] = qt[j];
qt[j] = tempqt;
}
}
}
for(i=0; i<5; i++)
{
cout << i+1 << ".number: " << qt[i] << endl;
}
通常,2个for循环对我的数组进行排序,最后一个for循环显示我的数组排序,所以它看起来像这样:
- 1.数量:10
- 2.数量:10
- 3.数量:20
- 4.数量:20
- 5.数量:50
但我想显示与相同排名位置具有相同值的数字,所以如下所示:
- 1.数量:10
- 1.数量:10
- 2.数量:20
- 2.数量:20
- 3.数量:50
这个想法是在qt
数组中遇到不同值时增加rank
计数器。
i = 0;
int rank = 1, val = qt[i];
cout << rank << ".number: " << qt[i] << endl;
for(i=1; i<5; i++)
{
if (qt[i] != val) {
++rank;
val = qt[i];
}
cout << rank << ".number: " << qt[i] << endl;
}
使用std::sort
对数组进行排序--只有对数组进行了排序,才能获得任何结果。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int qt[5] = { 10, 20, 10, 50, 20 };
sort(qt, qt + 5);
int count = 1;
for (int i = 0; i < 5; ++i)
{
if (i > 0)
{
if (qt[i] != qt[i - 1])
++count;
}
cout << count << ".number: " << qt[i] << endl;
}
}
这是另一个使用地图的解决方案。这更"懒惰",因为没有真正的"检查数字是否已经看到"逻辑。只需在地图上添加数字,然后循环打印出结果。
如果没有内存限制(当然,您需要创建一个数字映射),和/或您需要数组保持稳定(不排序),那么这可能是一个替代方案。
#include <map>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int qt[5] = { 10, 20, 10, 50, 20 };
std::map<int, int> IntMap;
// add entries to map, adding to a counter each time
for (int i = 0; i < 5; ++i)
IntMap[qt[i]]++;
// output the results.
int count = 1;
for (auto it = IntMap.begin(); it != IntMap.end(); ++it, ++count)
{
for (int i = 0; i < it->second; ++i)
cout << count << ".number: " << it->first << endl;
}
}
地图已经排序了,所以这已经处理好了。然后设置地图来计算每个数字出现的次数,这样就可以处理好了。剩下的就是编写一个循环,只需遍历地图并打印信息。
请在此处查看:http://ideone.com/q08SeX
我宁愿使用do-while循环:
int p = 1, x = 0;
do
{
cout << p << ".number: " << qt[x++] << endl;
if (x < 5 && qt[x] != qt[x-1])
p++;
} while (x < 5);
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 合并排序不排序自创建数组类 c++
- 带有枚举方向/类型的气泡排序结构数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 排序并行数组
- 如何在数组 c++ 中对字符串进行排序
- 为什么在此排序算法实现中,向量明显比数组慢?
- 如何对不在数组中的变量进行排序?
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 按字母顺序对结构内数组变量中的名称进行排序
- 使用排序函数 c++ 对字符数组进行排序
- 使用 std::sort 对二维 c 数组进行排序
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 对 0 、1 和 2 的数组进行排序