如何收集同类型Map的值
我们有一张映射,其键和值都是 int 类型。我们必须在映射中搜索特定值并将这些键收集到一个向量中。 代码快照就像
map<int,int>m;
map<int,int>::iterator itr;
vector<int> v;
m.insert(make_pair<int,int>(1,2));
m.insert(make_pair<int,int>(2,2));
m.insert(make_pair<int,int>(3,2));
m.insert(make_pair<int,int>(4,4));
m.insert(make_pair<int,int>(5,5));
当前代码就像:
for ( itr = m.begin(); itr != m.end(); ++itr )
{
if ((*itr).second == 2 )
v.push_back((*itr).first )
}
我们喜欢优化它。我们如何使用STL算法来做。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在我看来,你的处理方式是错误的,你可能想要一个多重地图。
It seems to me that you are going about this the wrong way, you probably want a multimap.
您可以将键与值交换(=所有值都不同)吗?如果是这样,您可以使用 map.find() (时间复杂度为 O(log n))来搜索项目。如果不是,您编写的代码就是正确的方法。
另一种方法是在地图填充值时创建向量,但这假设过滤标准在插入时已知。
Can you swap the key with the value (=are all values distinct)? If so you then can use map.find() (which is O(log n)) to search for items. If not the code you wrote is the correct approach.
Another approach would be to create the vector at the time the map get filled with values, but this assumes that the filter criterion is known at insertion time.
假设你确实有很多这样的映射,那么有
boost multi_index
,尽管它只是成对的整数,可能不再需要维护两个映射,后者是一个multimap< ; int、int >
或map< int,设置<整数> >
这将起作用Assuming you really do have a lot of them, there is
boost multi_index
, although with it just being pairs of ints it will probably be no more work to maintain two maps, the latter being amultimap< int, int >
, ormap< int, set< int > >
which will work如果需求可以改变,即键-值可以交换,则可以使用map。 > 并通过将数据推入与键对应的向量来构建地图。这样就可以在构建地图本身时对其进行优化。
如果要求不能像OP在评论之一中所说的那样改变,那么我认为没有太大的优化空间。
If at all the requirement could be changed, i.e. key - value could be swapped, one could go with a
map<int, vector<int> >
and build the map by pushing the data into the vector corresponding to the key. This way it could be optimized while building the map itself.If requirement can not be changed as OP has said in one of the comments, then i think there is not much scope for optimization.