我有一个std::list< std::pair<std::string,double> >
,我知道它是根据std::string element
排序的。
因为我想做很多基于std::string
元素的std::find_if
,所以我相信带有lower_bound
和upper_bound
的std::map<string,double,MyOwnBinaryPredicate>
会更合适。
事实上,我想以一种有效的方式在std::map
中使用insert
元素。所以我想使用一个额外的迭代器来使insert
更快。
我认为最简单的方法是使用const_reverse_iterator
遍历std::list
并使用std::map
的begin()
。
你会这样做吗,或者这是个坏主意?
谢谢!
发布于 2010-08-05 15:51:51
如果您已经有一个已排序列表,该列表根据谓词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 )。然后,您可以像使用任何其他地图一样直接使用该地图。
如果你以后想要结果回到你的列表中,你可以做相反的事情:
sorted_list.assign(map.begin(), map.end());
发布于 2010-08-05 15:49:53
您可以使用std::copy和std::inserter:
std::copy(the_list.begin(),the_list.end(),std::inserter(the_map,the_map.begin()));
因为list< pair >的迭代器具有与map< X,Y>的迭代器兼容的值类型。
发布于 2010-08-05 15:50:51
我只需迭代列表并将每一对都插入到映射中,或者使用Luther Blissett描述的整洁方法。
我不明白你想要做什么,这意味着它要么导致代码无法阅读,要么你走错了路。
你为什么要这样做呢?
您能否更改代码,首先向您返回一个地图,而不是一个列表?
https://stackoverflow.com/questions/3412623
复制相似问题