Better way to sort 2 “linked” arrays? [duplicate]

2019-09-19 05:27发布

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?

1条回答
仙女界的扛把子
2楼-- · 2019-09-19 06:03

you could use a std::map string to int that maps names to their index (which is the same index of ids), and if you want to order to ids too another std::map int to int that maps ids to their index (which is the same index of names).

this way you can keep your arrays as is and have two ordered structure which can give you the needed index fast to access your arrays.

查看更多
登录 后发表回答