我有一个 std::list< std::pair<std::string,double> >
,我知道这是根据 std::string element
排序的.
因为我想做很多std::find_if
基于 std::string
元素,我相信一个std::map<string,double,MyOwnBinaryPredicate>
与 lower_bound
和 upper_bound
会更合适。
事实是我想insert
std::map
中的元素以一种有效的方式。所以我想使用一个额外的迭代器来制作 insert
更快。
我相信最简单的方法是使用 const_reverse_iterator
通过 std::list
并使用 begin()
的 std::map
.
你会这样做吗,还是一个坏主意?
谢谢!
最佳答案
如果您已经有一个排序列表,它是根据谓词 Predicate
排序的,您可以执行以下操作:
std::list< std::pair<std::string, double> > sorted_list;
std::map<string, double, Predicate> map(sorted_list.begin(), sorted_list.end());
如果您的列表已经排序,map
构造函数具有线性时间复杂度,否则为 O(n*log n)。然后,您可以像使用其他任何东西一样直接使用 map 。
如果您稍后想要将结果返回到您的列表中,您可以做相反的事情:
sorted_list.assign(map.begin(), map.end());
关于c++ - 如何将已排序的 std::list of std::pair 转换为 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3412623/