如何将 std::pair 的排序 std::list 转换为 std::map
我有一个 std::list< std::pair
,我知道它是根据 std::string 元素
排序的。
由于我想基于 std::string
元素执行大量 std::find_if
操作,因此我相信 std::map
与 lower_bound
和 upper_bound
会更合适。
事实上,我想以有效的方式在 std::map
中插入
元素。所以我想使用一个额外的迭代器来使插入
更快。
我相信最简单的方法是使用 const_reverse_iterator 来遍历 std::list 并使用 begin()
代码>std::map。
你会这样做吗?或者这是一个坏主意?
谢谢!
I have got a std::list< std::pair<std::string,double> >
, which I know is sorted according to the std::string element
.
Since I would like to do a lot of std::find_if
based on the std::string
element, I believe a std::map<string,double,MyOwnBinaryPredicate>
with lower_bound
and upper_bound
would be more adequate.
The fact is that I want to insert
elements in the std::map
in an efficient way. So I want to use an additional iterator to make the insert
faster.
I believe the easiest way would be to use a const_reverse_iterator
to go through the std::list
and to use the begin()
of the std::map
.
Would you do it this way, or is it a bad idea?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您已经有一个根据谓词
Predicate
排序的排序列表,您可以执行以下操作:如果您的列表已经是,则
map
构造函数具有线性时间复杂度已排序,否则为 O(n*log n)。然后,您可以像使用其他地图一样直接使用该地图。如果您稍后希望将结果返回到列表中,您可以执行相反的操作:
If you already have a sorted list, which is sorted according to the predicate
Predicate
, you can just do the following:The
map
constructor has linear time complexity if your list is already sorted, O(n*log n) otherwise. You can then work directly with the map as you would any other.If you later want the results back in your list you could just do the opposite:
您可以使用 std::copy 和 std::inserter:
因为列表的迭代器<对>具有与 map< 兼容的值类型X,Y > 的迭代器。
You can use std::copy and std::inserter:
because the iterator for a list< pair > has a value type compatible to map< X,Y >'s iterators.
我只需迭代列表并将每一对插入到地图中或使用 Luther Blissett 描述的简洁方法。
事实上,我不明白你想要做什么,这意味着它要么会导致代码不可读,要么你就偏离了正轨。
你为什么要这样做?
您可以更改代码以首先返回地图而不是列表吗?
I would just iterate on the list and insert every pair into a map or use the neat method Luther Blissett has described.
The fact that I don't get what are you trying to do means it will either result in unreadable code or that you are way off.
Why are you doing it this way?
Can you change the code to return a map to you instead of a list in the first place?