简体   繁体   English

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

[英]How to sort multidimensional array by column in C++?

do you know how to sort a multidimensional array in C++? 你知道如何在C ++中对多维数组进行排序吗?

my input is like this: 我的输入是这样的:

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

And I want to sort it according to the 4th column in descending order, and my code including sort() function is like this: 我想按照降序对第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()

How to use this sort function to sort by the 4th column? 如何使用此排序功能按第四列排序? I'm really confused... 我真的很困惑

It's much easier to sort items when they are grouped into some structure. 将项目分组为某种结构时,对项目进行排序要容易得多。

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;
}

Arrays do not have the copy assignment operator. 数组没有副本分配运算符。 So you need to change the data structure used to store your data. 因此,您需要更改用于存储数据的数据结构。

Here is shown an approch with using the standard data structure std::array 这里显示了使用标准数据结构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;
    }
}    

The program output is 程序输出为

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 

If you want to sort the array in the descending order then the call of the std::sort will look like 如果要按降序对数组进行排序,则对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] );
           } );

If your compiler does not support auto in lambda expressions than you have to spesify the type of the parameters explicitly 如果您的编译器不支持lambda表达式中的auto,则必须明确指定参数的类型

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

Also you could consider to use an array of std::tuple 您也可以考虑使用std::tuple

Of course instead of an array of objects of std::array or type std::tuple you could use standard class std::vector . 当然,可以使用标准类std::vector代替std :: array或类型为std :: tuple的对象数组。

You goal : sort the records (I mean one line is one record) by the 4th column . 您的目标是:按第4列对记录进行排序(我的意思是一行是一条记录)。 so the next step is how to represent the every record , obviously, you need a combination type to represent the record;for example : (pseudo code) 因此,下一步是如何表示每条记录,显然,您需要一种组合类型来表示记录;例如:(伪代码)

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

The next method is not advisable: In 2 dimensions array, one record is one dimension array, example, arr[0][0] arr[0][1] arr[0][2] arr[0][3] represent first record, at the same time, arr[0] represent string[4] ! 不建议使用下一种方法:在2维数组中,一条记录是1维数组,例如arr [0] [0] arr [0] [1] arr [0] [2] arr [0] [3]表示第一条记录,同时arr [0]代表字符串[4]! Are you have any inspiration ? 你有什么灵感吗? follow is pseudo code: 以下是伪代码:

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 } }

In a word , first method deserved your try ; 总之, 第一种方法应该得到你的尝试 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM