首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++按第二个值对数组进行排序

C++按第二个值对数组进行排序
EN

Stack Overflow用户
提问于 2021-09-03 00:17:43
回答 3查看 188关注 0票数 1

我刚开始学习C++,我想知道是否有一种方法可以按每个数组中的第二个值对二维数组进行排序。我还没有在网上找到任何方法,所以我在这里询问。

例如,您可以从以下位置开始:

代码语言:javascript
复制
int exampleArray[5][2] = {
    {4, 20},
    {1, 4},
    {7, 15},
    {8, 8},
    {8, 1}
};

在排序之后,数组将是

代码语言:javascript
复制
int exampleArray[5][2] = {
    {8, 1},
    {1, 4},
    {8, 8},
    {7, 15},
    {4, 20}
};

在Python语言中,您可以使用exampleArray.sort(key = lambda element : element[1])对其进行排序,但我不知道如何使用C++对其进行排序

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-09-03 01:09:10

简短的答案是:不要那样做。C++从C继承了它的内置数组,它并不能很好地适应你想要做的事情。

合理相似且易于实现的方法是使用std::vector而不是数组。

代码语言:javascript
复制
std::vector<std::vector<int>> someVector {
    {4, 20},
    {1, 4},
    {7, 15},
    {8, 8},
    {8, 1}
};

根据每行中的第二项对其进行排序非常简单:

代码语言:javascript
复制
    std::sort(someVector.begin(), someVector.end(), 
        [](auto const &a, auto const &b) { return a[1] < b[1]; });

然后我们可以打印出结果来验证它是否如预期的那样工作:

代码语言:javascript
复制
for (auto const &row : someVector)
    std::cout << row[0] << "\t" << row[1] << "\n";

正如您所期望的,这会产生:

代码语言:javascript
复制
8   1
1   4
8   8
7   15
4   20
票数 3
EN

Stack Overflow用户

发布于 2021-09-03 01:31:18

您可以使用结构来保存您的数据:

代码语言:javascript
复制
struct Data
{
    int x,y;
};
vector<Data> a;

使用std::sort,您可以使用lambda函数来实现您的目标

std::sort(a.begin(),a.end(),[](Data e1,Data e2){return e1.y<e2.y;});

票数 0
EN

Stack Overflow用户

发布于 2021-09-03 01:38:21

使用向量要简单得多,但是假设您不能使用std::vector,这里有一种基于answer given here的“排序”的替代方法

代码语言:javascript
复制
#include <iostream>
#include <algorithm>

int main()
{
    int exampleArray[5][2] = {
        {4, 20},
        {1, 4},
        {7, 15},
        {8, 8},
        {8, 1}
    };

    // create the indexing (there are 5 2D entries)
    int index[] = {0,1,2,3,4};

    // sort the index based on the second value in the 2D array    
    std::sort(index, index + 5, [&](int n1, int n2) 
             { return exampleArray[n1][1] < exampleArray[n2][1]; });

    // output results
    for (int i = 0; i < 5; ++i)
       std::cout << exampleArray[index[i]][0] << " " << exampleArray[index[i]][1] << "\n";
}

输出:

代码语言:javascript
复制
8 1
1 4
8 8
7 15
4 20

基本上,您希望根据2D数组中的第二个值对索引数组进行排序。这就是lambda函数所说的--索引数组被“排序”,而不是原始的2D数组。

排序完成后,使用索引数组以排序的方式访问2D数组中的项。

在此基础上,如果希望将更改存储在实际的2D数组中,则可以使用排序后的索引重新构建原始数组:

代码语言:javascript
复制
    // rebuild the original array using the sorted index
    int tempArray[5][2] = {};
    for (int i = 0; i < 5; ++i)
    {
        tempArray[i][0] = exampleArray[index[i]][0];
        tempArray[i][1] = exampleArray[index[i]][1];
    }
    
    // copy the new sorted array to the original array
    memcpy(exampleArray, tempArray, sizeof(exampleArray));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69038256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档