find_if

This is a discussion on find_if within the C++ Programming forums, part of the General Programming Boards category; I have a vector of pair<string, int>. Now I want to detect if there's an item in the vector where ...

  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,893
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21