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