Search code examples
c++arrayssortingmultidimensional-arraybubble-sort

How do I sort a 2d string array by a specific column's values in C++?


I have the following 2d array that I get/create from an external .txt file.

string accountsArr[5][7] = {
  "bham@gnet.com", "Blake", "Ham", "squid62", "1987", "U", "Teacher",
  "jdark@att.net", "Jim", "Dark", "gymrat32", "1985", "A", "Master",
  "hgreen@lakes.net", "Hannah", "Green", "flower22", "2007", "U", "Apprentice",
  "tsmith@dna.com", "Tom", "Smith", "tuna20", "2000", "U", "Teacher",
  "jarrow@pnet.com", "James", "Arrow", "ahoy10", "2005", "U", "Apprentice"
};

I need to sort this array based on the "last name" column (column index 2 for each row), so I basically end up with:

string accountsArr[5][7] = {
  "jarrow@pnet.com", "James", "Arrow", "ahoy10", "2005", "U", "Apprentice",
  "jdark@att.net", "Jim", "Dark", "gymrat32", "1985", "A", "Master",
  "hgreen@lakes.net", "Hannah", "Green", "flower22", "2007", "U", "Apprentice",
  "bham@gnet.com", "Blake", "Ham", "squid62", "1987", "U", "Teacher",
  "tsmith@dna.com", "Tom", "Smith", "tuna20", "2000", "U", "Teacher"
};

How would I do this, programmatically? Using std::sort isn't working. I keep getting use of undeclared identifier sort.

int n = sizeof(accountsArr[0]) / sizeof(accountsArr[0][0]);
std::sort(accountsArr, accountsArr + n);

UPDATE: I need/want to know how to do this on a primitive string array specifically (no vectors, structs, etc).


Solution

  • So I finally figured this out by doing a "bubble sort". Here's how I implemented it. Hopefully this can help someone else who's having trouble finding any examples of sorting with 2d arrays by a specific column:

    int rows = 5;
    int col = 7;
    string accountsArr[rows][col] = {
      "bham@gnet.com", "Blake", "Ham", "squid62", "1987", "U", "Teacher",
      "jdark@att.net", "Jim", "Dark", "gymrat32", "1985", "A", "Master",
      "hgreen@lakes.net", "Hannah", "Green", "flower22", "2007", "U", "Apprentice",
      "tsmith@dna.com", "Tom", "Smith", "tuna20", "2000", "U", "Teacher",
      "jarrow@pnet.com", "James", "Arrow", "ahoy10", "2005", "U", "Apprentice"
    };
    
    //do a bubble sort
    for(int maxElement = rows - 1; maxElement > 0; maxElement--){
      for(int i = 0; i < maxElement; i++){
        //if current row "last name" column is > the next row "last name" column, swap them
        if(theAccounts[i][2] > theAccounts[i + 1][2]){
          std::swap(theAccounts[i], theAccounts[i + 1]);
        }
      }
    }