-2

I'm trying to take input from two different vectors into an unordered_map but getting error

vector<string> sortPeople(vector<string>& names, vector<int>& heights)      {
  vector<string> result;
  unordered_map<int, string> mp;
  for (auto s : names) {
     for (auto t : heights) {
        sort(heights.rbegin(),heights.rend());
        mp[heights].push_back(names);
     }
  }
  for (itr : mp) {
     result.push_back(mp.second);
  }
  return result;     }
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 05 '22 at 07:56

1 Answers1

1

I'm guessing you're just trying to sort "names" by their corresponding "height".

If so, just copy each name/height pair into an intermediate object and sort on that using a custom sort function.

I'm assuming names.size() == heights.size()

Not sure if you want to return the list from tallest to shortest or shortest to tallest. I went with the latter. Easy fix if you want the former.

#include <vector>
#include <algorithm>
#include <string>

using namespace std;

vector<string> sortPeople(vector<string>& names, vector<int>& heights) {

    typedef pair<int, string> Person;

    vector<Person> people;
    for (size_t i = 0; i < names.size(); i++) {
        Person person = {heights[i], names[i]};
        people.push_back(person);
    }

    std::sort(people.begin(), people.end(), [] (const Person& p1, const Person& p2) {
        return (p1.first == p2.first) ? (p1.second < p2.second) : (p1.first < p2.first);
    });
    
    vector<string> result;
    for (const auto& person : people) {
        result.push_back(person.second);
    }
    return result;
}

You can even sort by indices and avoid some redundant copies.

vector<string> sortPeople(vector<string>& names, vector<int>& heights) {

    // people is a list of indices from 0..N-1
    auto people = std::vector<size_t>(names.size());
    std::iota(people.begin(), people.end(), 0);


    std::sort(people.begin(), people.end(), [&] (size_t p1, size_t p2) {
        return (heights[p1] == heights[p2]) ? (names[p1] < names[p2]) : (heights[p1] < heights[p2]);
    });

    vector<string> result;
    for (int person : people) {
        result.push_back(names[person]);
    }
    return result;
}
selbie
  • 100,020
  • 15
  • 103
  • 173
  • FWIW, I like to replace the first `for` loop by `std::iota(people.begin(), people.end(), 0);` (needs `#include `). – j6t Oct 05 '22 at 07:19
  • @j6t - thank you. I knew there was a function that could do that, I just couldn't recall it. I'll update. – selbie Oct 05 '22 at 07:57
  • After re-reading, I see I should have been more careful. That should be `size_t{0}` (or `0uz` in C++23) instead of plain `0` to match the type in the `vector`. – j6t Oct 05 '22 at 08:18