简体   繁体   中英

Finding An Object In a Vector, with multiple requirements

I have created a vector of objects, and the objects have multiple private variables:

   Int x, y, id

Now i wish to iterate through this vector, and find the object just before my x and y values. The smallest value for which x & y are greater.

I've seen the vector "find" command. Could this accept multiple arguments in it's final field... Something like

(Vector.begin, vector.end, (x > object.x && y > object.y)

I've been messing around with it and googling to find a solution but I've not seen any examples involving multiple arguments in the last field of the find command?

You can use std::find_if with a lambda

Object foo;                // object you want to compare against
std::vector<Object> objs;  // objects you want to look through
auto itFound = std::find_if(begin(objs),
                            end(objs),
                            [&foo](Object const& obj)
                            {
                                return obj.x > foo.x && obj.y > foo.y;
                            });

You can call find_if with a functor or lambda that tests all the conditions you please.

http://en.cppreference.com/w/cpp/algorithm/find

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM