Click to See Complete Forum and Search --> : Search (Compare) Functor and std::pair :: STL


kuphryn
December 21st, 2002, 09:54 PM
Hi.

How do you definte a comparison function for an container of std::pair other than map? I need to search a container of std::pair. For example:


typedef std::deque<std::pair<std::string, int> > deqStringInt;

deqStringInt example;
example.push_back(std::pair<"December", 21>);

// How do you search an element?

std::find_if(example.begin(), example.end(), std::bind2nd(???

// Functor
class Search : std::binary_function<std::pair<std::string, int>, std::string, bool>
{
public:
bool operator()(const std::pair<std::string, int> &lp, const std::string &rp)
{
return lp->first == rp;
}
};


Thanks,
Kuphryn

DanM
December 23rd, 2002, 12:24 AM
#include <map>
#include <deque>
#include <algorithm>
#include <string>
#include <iostream>

using namespace std;

typedef pair<string, int> stringIntPair;
typedef deque<stringIntPair> deqStringInt;

bool isEq(stringIntPair a_pair, string a_string)
{
return (a_pair.first == a_string);
}
void f1()
{


deqStringInt example;
example.push_back(stringIntPair("December", 21));

deqStringInt::iterator iter1 = find_if(example.begin(),
example.end(),
bind2nd(ptr_fun(isEq), string("December")));

if (iter1 != example.end())
cout << iter1->first << endl;
else
cout << "No value" << endl;

}

Dan

kuphryn
December 23rd, 2002, 10:58 AM
Nice! Thanks.

What is the purpose of std::ptr_fun?

Kuphryn

DanM
December 23rd, 2002, 11:14 AM
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcstdlib/html/vclrf_functional_ptrfun.asp

Dan