使用第二列C ++对2D数组排序 [英] Sorting a 2D array using the second column C++

查看:94
本文介绍了使用第二列C ++对2D数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须根据第二列对2D等级和名称数组(用作字符串)进行排序。我正在尝试按字母顺序对其进行排序,但似乎无法正确处理。我还是多维数组的新手,所以我还是很困惑。我正在使用气泡排序,它正在对名称进行排序,但顺序不正确。

I have to sort a 2D array of ranks and names (used as strings) based on the second column. I'm trying to sort it in alphabetical order but I can't seem to get it right. I'm still new to multi-dimensional arrays, so I'm still quite confused. I'm using Bubble Sort, and it is sorting the names, but not in the right order.

这是我要排序的数组:

const int ROWS=6;
const int COLS=2;

string names [ROWS][COLS] = { "1", "Jacob",
                              "2", "Michael",
                              "3", "Joshua",
                              "4", "Matthew",
                              "5", "Ethan",
                              "6", "Andrew"};

这就是我得到的:

2 Michael
4 Matthew
3 Joshua
1 Jacob
6 Andrew
5 Ethan

这是我正在使用的排序函数:

and this is the sort function I'm using:

void sort (string names [][COLS], int size)
{    
    int i,j; // i = rows 
    string hold1, hold2;

    for (i=0; i < size-1; i++)
    {
        for (j=0; j < size; j++)
        {
            if (names [i][1] > names [j][1]) //names  = col 1 , rank = col 0
            {
                hold1 = names [i][1];
                hold2 = names [i][0];
                names [i][1] = names [j][1];
                names [i][0] = names [j][0];
                names [j][1] = hold1;
                names [j][0] = hold2;
            }
        }
    }
}

提前。

推荐答案

您实际上是来回交换元素。您需要确保在进行冒泡排序时,仅将一个元素与一个以后元素进行比较。即:

You're actually swapping the elements back and forth. You need to make sure that when you're Bubble Sorting you're only comparing an element with a later element. That is:

for (i=0; i < size-1; i++)
{
    for (j=i+1; j < size; j++)
          ^^^^
    {
        // same as before
    }
}

请注意,我们可以利用标准实用程序使此代码更易于理解。我写为 //的行与以前一样 ...您在这里所做的只是交换名称[i] 名称[j] ,我们可以将其拼写为:

Note that we can take advantage of standard utilities to make this code a lot easier to understand. The line I wrote as //same as before... what you're doing there is just swapping names[i] and names[j], which we can spell:

std::swap(names[i], names[j]);

这更容易理解,而且不易出错。

That's just easier to understand and less error-prone.

这篇关于使用第二列C ++对2D数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆