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

半世苍凉 提交于 2020-01-17 06:20:31

问题


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:


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.



来源:https://stackoverflow.com/questions/39251752/better-way-to-sort-2-linked-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!