Griffinflame
Griffinflame

Reputation: 21

C++ How would I use sort to sort this two dimensional array?

My question is pretty specific, I think. My program is supposed to store 10 names, and their corresponding phone numbers into an array. I want to sort the names/numbers by phone numbers, ascending order, and then output the array in the sorted order. Thanks for the help! Any and all help is appreciated. What I have so far:

using namespace std;

main()
{
    string name[10][2];
    int x;

    cout << "Please input 10 names";
    for(int i = 0; i < 10; i++){
        cin >> name[i][x];
    }
    int i = 0;
    cout << "Please input their corresponding numbers";
    for(x = 0; x < 10; x++){
        cin >> name[i][x];
    }
}

EDIT: Would it be possible(not as hassling) to instead do this but with a parallel array storing a string(name) and an int(number) and sort it by the int?(Of course, while keeping the names by their corresponding number) If so, how could I change it from a two-dimensional to a parallel array?(Or just pointing me in the right direction would be greatly appreciated) :)

Upvotes: 0

Views: 87

Answers (1)

Henri Menke
Henri Menke

Reputation: 10939

You will want to use a vector of pairs. This is in this case more convenient than a map because you want to sort by value rather than by key. There are also methods to sort a map by value (see question Sorting std::map using value), but for this purpose a vector of pairs seems appropriate.

If you want to have a constant memory array instead of a dynamic memory array (std::vector) then use std::array<std::pair<std::string,int>, N>, where N is the number of elements.

Needs C++14 because of the template lambda.

#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>

int main()
{
  std::vector<std::pair<std::string,int>> phonebook;
  phonebook.reserve(10);

  std::cout << "Please input a name and a number\n";
  for (int i = 0; i < 10; ++i) {
    std::cout << "Name: ";
    std::string name;
    std::cin >> name;

    std::cout << "Number: ";
    int number;
    std::cin >> number;

    phonebook.push_back({name, number});
  }

  std::sort( std::begin(phonebook),
             std::end(phonebook),
             [] (auto a, auto b) { return a.second < b.second; });

  for (auto const& entry : phonebook)
  {
    std::cout << entry.first << ' ' << entry.second << '\n';
  }
}

Upvotes: 1

Related Questions