I have 2 vectors which store properties that are "linked". This is what I mean:
std::vector<std::string> names;
std::vector<int> ids;
// Name of object with an ID of 5
auto name = names[std::find(ids.begin(), ids.end(), 5) - ids.begin()];
Each object has a name and an ID, and so the object at index n has a name of name[n]
and an ID of ids[n]
.
Now I want to sort the names in alphabetical order. I can use std::sort
:
std::sort(names.begin(), names.end());
But now the IDs don't match! I thought of doing a vector of pairs, putting every name/id in it, sorting it, and then extracting out the data.
This isn't really efficient, as I have to loop 2 times over every element of both vectors, and the vectors have a lot of elements.
How can I make it more efficient, seeing that I can't use the vector of pairs instead of the 2 vectors from the beginning?