如何按价值有效地订购地图? [英] How can I order a map by value efficiently?
问题描述
考虑一个 std :: map< K,V>
。我想通过一个合适的容器 std :: C< V *>
或 std :: C< V& ;>
,在某种意义上没有值的副本来存储C中的元素。此外,C中的元素必须根据 int f V&)
应用于每个元素。尽管我的努力,我找不到一个合适的C和一个足够的有效的方式来构建它。你有什么解决方案吗?
Consider a std::map<K,V>
. I want to re-order the map by value profiting by an appropriate container std::C<V*>
or std::C<V&>
, in a way that no copies of values are done to store the elements in C. Furthermore, elements in C must be sorted according to the result of int f(V&)
applied to each element. Despite my efforts I could not find an appropriate C and an enough efficient way to build it. Do you have any solution? A small example would be much appreciated.
推荐答案
看起来很简单。
std::map<K,V> src;
int f(V&) {return 0;}
V* get_second(std::pair<const K,V> &r) {return &(r.second);} //transformation
bool pred(V* l, V* r) { return f(*l)<f(*r); } //sorting predicate
std::vector<V*> dest(src.size()); //make destination big enough
std::transform(src.begin(), src.end(), dest.begin(), get_second); //transformcopy
std::sort(dest.begin(), dest.end(), pred); //sort
除非你的意思是C应该是另一个地图:
Unless you meant C is supposed to be another map:
std::pair<K,V*> shallow_pair(std::pair<const K,V> &r)
{return std::pair<K,V*>(r.first, &(r.second));}
std::map<K, V*> dest2;
std::transform(src.begin(), src.end(),
std::inserter(dest2,dest2.end()), shallow_pair);
这需要上一张地图保持在更长的时间 dest
,并且在 dest
被销毁之前没有删除对。否则 src
将需要保存某种类型的智能指针。
This requires the previous map to remain in scope longer than dest
, and have no pairs removed until dest
is destructed. Otherwise src
will need to have been holding smart pointers of some sort.
这篇关于如何按价值有效地订购地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!