如何在C++中按列对多维数组进行排序?

问题描述 投票:0回答:4

你知道如何在 C++ 中对多维数组进行排序吗?

我的输入是这样的:

Bogaerts_X  144 12  138
Cespedes_Y  51  5   48
Gomes_J     78  6   70
Holt_B      106 4   98
Napoli_M    119 17  133
Nava_D      113 4   81
Ortiz_D     142 35  95
Pedroia_D   135 7   75
Pierzynski_A72  4   40
Ross_D      50  7   58

我想按照第4列降序排列,我的代码包括sort()函数是这样的:

#include <iostream>
#include <fstream>  //Required for fin.open, fin.close, fout.open, fout.close
#include <cstdlib>  //Required for srand(), rand().
#include <ctime>    //Required for time(NULL) to seed the random num gen

using namespace std;


// Declaration of the main function
int main()
{
    ofstream fout;
    ifstream fin;
    string array[100][100];
    int limit(0);

    fin.open("312.txt" );

    cout << " -------------------------------" << endl << endl;

    for (int i=0; i<12; ++i)    //every row
    {
        for (int j=0; j<4; ++j )//every col
        {
            fin >> array[i][j];
        }
    }

    for (int i=0; i<12; ++i)    //every row
    {
        for (int j=0; j<4; ++j )//every col
        {
            cout << "\t" << array[i][j];
        }
        cout << endl;
    }


    //sort players according to the 4th column




    //Asks the user for a limit of home runs to search by
    cout << "Give me the limit of home runs to search by"<<endl;
    cin >> limit;


    //sorted alphabetically and displays
    for (int i=0; i<limit; ++i) //every row
    {
        for (int j=0; j<4; ++j )//every col
        {
            cout << "\t" << array[i][j];
        }
        cout << endl;
    }


    fin.close();

    cout << endl << endl << endl << endl << endl << endl << endl;

    // Exit program.
    return 0;
}

//This sample function sorts the array with n elements
//into ascending order using selection sort

void sort(const double a[], int n)
{
    double temp; int m; int x[0];
    for (int k=0; k<=n-2; ++k) {
        //find position of smallest element beginning at k
        m = k;
        for (int j=k+1; j < n-1; ++j)
            if (a[j] < a[m])
                m = j;
        //exchange smallest value with value at k
        temp = x[m];
        x[m] = x[k];
        x[k] = temp;
    } //end for (k)
} //end sort()

如何使用这个排序功能按第4列排序?我真的很困惑......

c++ arrays algorithm sorting multidimensional-array
4个回答
3
投票

当项目被分组到某种结构中时,对它们进行排序要容易得多。

struct Data
{
    std::string name_;
    int x_, y_, z_;
};

int main()
{
    std::vector<Data> data;

    Data d1 = { "Bogaerts_X", 144, 12, 138 };
    Data d2 = { "Cespedes_Y", 51, 5, 48 };

    data.push_back(d1);
    data.push_back(d2);

    std::sort(std::begin(data), std::end(data), [](const Data& a, const Data& b)
    {
        // sort based on the last member variable or 4th column in your case
        return a.z_ < b.z_;
    });

    return 0;
}

2
投票

数组没有复制赋值运算符。因此,您需要更改用于存储数据的数据结构。

这里显示了一个使用标准数据结构的方法

std::array

#include <iostream>
#include <array>
#include <algorithm>
#include <string>
#include <iterator>

int main()
{
    std::array<std::string, 4> data[] =
    {
        { { "Bogaerts_X",  "144", "12",  "138" } },
        { { "Cespedes_Y",   "51",  "5",   "48" } },
        { { "Gomes_J",      "78",  "6",   "70" } },
        { { "Holt_B",      "106",  "4",   "98" } },
        { { "Napoli_M",    "119", "17",  "133" } },
        { { "Nava_D",      "113",  "4",   "81" } },
        { { "Ortiz_D",     "142", "35",   "95" } },
        { { "Pedroia_D",   "135",  "7",   "75" } },
        { { "Pierzynski_A", "72",  "4",   "40" } },
        { { "Ross_D",       "50",  "7",   "58" } }
    };

    for ( const auto &row : data )
    {
        for ( const auto &s : row ) std::cout << s << ' ';
        std::cout << std::endl;
    }

    std::cout << std::endl;

    std::sort( std::begin( data ), std::end( data ),
               []( const auto &a, const auto &b )
               {
                   return std::stoi( a[a.size() - 1] ) < std::stoi( b[b.size() - 1] );
               } );

    for ( const auto &row : data )
    {
        for ( const auto &s : row ) std::cout << s << ' ';
        std::cout << std::endl;
    }
}    

程序输出为

Bogaerts_X 144 12 138 
Cespedes_Y 51 5 48 
Gomes_J 78 6 70 
Holt_B 106 4 98 
Napoli_M 119 17 133 
Nava_D 113 4 81 
Ortiz_D 142 35 95 
Pedroia_D 135 7 75 
Pierzynski_A 72 4 40 
Ross_D 50 7 58 

Pierzynski_A 72 4 40 
Cespedes_Y 51 5 48 
Ross_D 50 7 58 
Gomes_J 78 6 70 
Pedroia_D 135 7 75 
Nava_D 113 4 81 
Ortiz_D 142 35 95 
Holt_B 106 4 98 
Napoli_M 119 17 133 
Bogaerts_X 144 12 138 

如果你想按降序对数组进行排序,那么 std::sort 的调用看起来像

std::sort( std::begin( data ), std::end( data ),
           []( const auto &a, const auto &b )
           {
               return std::stoi( b[b.size() - 1] ) < std::stoi( a[a.size() - 1] );
           } );

如果您的编译器不支持 lambda 表达式中的 auto,那么您必须明确指定参数的类型

[]( const std::array<std::string, 4> &a, const std::array<std::string, 4> &b )

你也可以考虑使用一组

std::tuple

当然,您可以使用标准类

std::vector
.

,而不是 std::array 或类型 std::tuple 的对象数组

0
投票

您的目标:按第 4 列对记录(我的意思是一行是一条记录)进行排序。所以下一步是如何表示每条记录,显然, 你需要一个组合类型来表示记录;例如:(伪代码)

class Record{
    //成员变量
    char *name;
    int age;
    int date;
    float score;
    Record(){/* constructure */}
    ~Record(){/* distructure*/}
    //成员函数
    void sort(/*arguments*/){/*bubble sort . selection sort . quick sort*/}
};

下一个方法不可取: 在二维数组中,一条记录就是一维数组,例如,arr[0][0] arr[0][1] arr[0][2] arr[0][3] 表示第一条记录,同时, arr[0] 代表 string[4] !你有什么灵感吗?以下是伪代码:

void bubble_sort(string ** array, int first_dimension_length, int sort_column){
    string mini = "2100000000";
    int mini_row = 0;
    string * swap = NULL; 
    for(int i = 0; i < first_dimension_length; ++i){
        for(int j = i + 1; i < first_dimension_length; ++j){
            if(mini > array[j][sort_column]){
                mini = array[j][sort_column];
                mini_row = i;
            }
        }
        swap = array[i]; 
        // swap point to one dimension array, that's swap is a pointer
        array[i] = array[mini_row]; 
        //array[i] also point to one dimension array
        array[mini_row] = swap; 
        //array[mini] also point to one dimension array
    }
}

一句话,第一种方法值得你尝试;


0
投票
struct Data
{
    std::string name_;
    int x_, y_, z_;
};

int main()
{
    std::vector<Data> data;

    Data d1 = { "Bogaerts_X", 144, 12, 138 };
    Data d2 = { "Cespedes_Y", 51, 5, 48 };

    data.push_back(d1);
    data.push_back(d2);

    std::sort(std::begin(data), std::end(data), [](const Data& a, const Data& b)
    {
        // sort based on the last member variable or 4th column in your case
        return a.z_ < b.z_;
    });

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.