std::mapその要素を でソートしますkeys。valuesいつソートするかは気にしません。
を使用std::vector<std::pair<K,V>>して並べ替えることができ、その後に次のものstd::sortが続きstd::stable_sortます。
std::vector<std::pair<K,V>> items;
//fill items
//sort by value using std::sort
std::sort(items.begin(), items.end(), value_comparer);
//sort by key using std::stable_sort
std::stable_sort(items.begin(), items.end(), key_comparer);
std::sortであるため、最初の並べ替えを使用し、最悪の場合はどちらをnlog(n)使用する必要があります。std::stable_sortn(log(n))^2
std::sortwhileはパフォーマンス上の理由から選択されていることに注意してくださいstd::stable_sort。値による順序を保持する必要があるため、正しい順序付けに必要です。
コメントに記載されている@gsfは、最初に比較する比較子を選択した場合にのみ 使用でき、それらが等しい場合は.std::sortvalueskeys
auto cmp = [](std::pair<K,V> const & a, std::pair<K,V> const & b)
{
return a.second != b.second? a.second < b.second : a.first < b.first;
};
std::sort(items.begin(), items.end(), cmp);
それは効率的なはずです。
しかし、待ってください。より良いアプローチがあります: storestd::pair<V,K>の代わりにstd::pair<K,V>比較子はまったく必要ありません — 標準の比較子 forでstd::pair十分firstです。VsecondK
std::vector<std::pair<V,K>> items;
//...
std::sort(items.begin(), items.end());
それはうまくいくはずです。