std :: map find

编程入门 行业动态 更新时间:2024-10-11 11:19:17
本文介绍了std :: map find_if条件样式混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用std :: find_if来搜索地图中在其值结构的特定元素中具有特定值的第一个元素。我有点困惑。我想我需要使用bind1st或bind2nd,但我不是积极的,这是正确的方式。

I'd like to use std::find_if to search for the first element in my map that has a certain value in a specific element of its value structure. I'm a little confused though. I think I need to use bind1st or bind2nd, but I'm not positive that's the right way to go.

这里有一些伪代码:

struct ValueType { int x, int y, int z }; std::map<int, ValueType> myMap; ... {populate map} std::map<int, ValueType>::iterator pos = std::find_if(myMap.begin(), myMap.end(), <?>);

因此,假设我想找到地图的第一个元素, ValueType等于某个整数值(它可以改变每个调用)。

So, let's say that I wanted to find the first element of the map where the .x member of the ValueType was equal to a certain integer value (which can change each call).

什么是最好的方式来写一个函数或函数对象来实现呢?我明白,必须是一个一元谓词,使我认为我需要bind1st或bind2nd提供我检查的整数值,但我不知道如何去。这是太长了,因为我看着这些东西! >。

What would be the best way to write a function or function object to achieve this? I understand that the has to be a unary predicate which makes me think I'll need bind1st or bind2nd to provide the integer value I'm checking for, but I'm not sure how to go about it. It's been way too long since I looked at this stuff! >.<

推荐答案

地图中的元素不按值排序,它们根据键排序。所以第一个元素这个短语没有多大意义。

Elements in the map are not sorted by value, they are sorted according to the key. So the phrase "the first element" has not much sense.

要查找元素(不是第一个) x 等于某个值,你可以写如下的函子:

To find some element (not the first) that has x equal to some value you can write the functor as follows:

struct check_x { check_x( int x ) : x_(x) {} bool operator()( const std::pair<int, ValueType>& v ) const { return v.second.x == x_; } private: int x_; };

然后使用它如下:

// find any element where x equal to 10 std::find_if( myMap.begin(), myMap.end(), check_x(10) );

更多推荐

std :: map find

本文发布于:2023-11-30 14:36:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650348.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:std   map   find

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!