My std::map
has pair of 'unique key' and 'unique value'. I usually find a key for a value and find a value for a key as well as.
I already know the method which by using std::find_if
+ lambda, however I want to know if there are any better ways.
After searching, I've found this article and I've learned how to use `std::binary_function'. Using both approach, I've checked 'elapsed time'. This is my code.
typedef int USER_ID;
typedef std::string USER_NICK_NAME;
typedef std::map<USER_ID, USER_NICK_NAME> USER_MAP;
template<class T>
struct map_data_compare : public std::binary_function<typename T::value_type, typename T::mapped_type, bool>
{
public:
bool operator() (typename T::value_type &pair, typename T::mapped_type i) const
{
return pair.second == i;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
USER_MAP user_map;
string nick_prefix = "test";
//make test map
for (int i = 0; i < 100000; i++)
{
std::ostringstream stream;
stream << i;
user_map.insert(USER_MAP::value_type(i, nick_prefix + stream.str()));
}
const USER_NICK_NAME nick_name = "test99999";
clock_t t;
//Method 1 : using find_if + lambda
cout << "Method 1 : using find_if + lambda" << endl;
t = clock();
auto it = std::find_if(user_map.begin(), user_map.end(), [&](const USER_MAP::value_type& user)
{
return nick_name == user.second;
});
if (it != user_map.end())
{
cout << "found nickname " << nick_name.c_str() << ", at index " << it->first << endl;
}
t = clock() - t;
cout << "elapsed " << ((float)t)/CLOCKS_PER_SEC << " seconds" << endl;
cout << endl << endl;
//Method 2 : using find_if + binary_function
cout << "Method 2 : using using find_if + binary_function" << endl;
t = clock();
it = std::find_if(user_map.begin(), user_map.end(), std::bind2nd(map_data_compare<USER_MAP>(), nick_name));
if (it != user_map.end())
{
cout << "found nickname " << nick_name.c_str() << ", at index " << it->first << endl;
}
t = clock() - t;
cout << "elapsed " << ((float)t)/CLOCKS_PER_SEC << " seconds" << endl;
return 0;
}
In my machine, Method 1 is always faster than Method2.
This is test result console.
So, My question is,
- In my situation(I mean searching map by value),
find_if
+ lambda is the best way? (Unfortunately, I can't use boost library.) - When I use
std::binary_function
? - I know that in C++ 11, `std::binary_function' has bee deprecated. Could I know the reason?
Thank you for your time to view this thread and for trying to help.