1

do you know how to sort a multidimensional array in 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:

#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...

1
  • 1
    I just would suggest you to use a std container like array for fixed size or vector, then use the std sort funtion with a lambda as key. Commented Nov 24, 2015 at 11:50

3 Answers 3

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

How do you print the contents of data?
2

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

#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::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

[]( 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

Of course instead of an array of objects of std::array or type std::tuple you could use standard class std::vector.

Comments

0

You goal : sort the records (I mean one line is one record) by the 4th column . 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] ! 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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.