c++排序:具有相同数组值的排序列表

c++ sort: ranking list with same value of an array

本文关键字:排序 数组 列表 c++      更新时间:2023-10-16

我试图显示我的数组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);