我想使用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
发布评论