Thread: find_if

  1. #1
    The larch
    Join Date
    May 2006
    Posts
    3,573

    find_if

    I have a vector of pair<string, int>. Now I want to detect if there's an item in the vector where first is equal to some other string.

    I wonder if someone might be able to show how to do this with <algorithm> (and perhaps <boost/lambda>) without creating a separate functor for the find_if algorithm (as that would be used only in one place).

    (Sorry, I've had some wine and can't seem to figure this one out )
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  2. #2
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Member access. Tricky business. Without testing, I think something like this ought to work.

    Code:
    #include <functional>  // equal_to
    #include <algorithm>   // find_if
    #include <string>   // string
    #include <utility>   // pair
    #include <vector>  // vector
    #include <boost/bind.hpp>    // bind
    
    // ...
    typedef std::pair<std::string, int> si_pair;
    typedef std::vector<si_pair> si_pair_vector;
    si_pair_vector vec;
    // ...
    
    std::string needle = whatever();
    si_pair_vector::iterator it = std::find_if(vec.begin(), vec.end(),
      boost::bind(std::equal_to<std::string>(),
        boost::bind(&si_pair::first, boost::_1), needle));
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  3. #3
    The larch
    Join Date
    May 2006
    Posts
    3,573
    Thanks, this indeed works.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed