我的std::map
有一對'唯一鍵'和'唯一值'。我通常找到一個關鍵值,並找到一個關鍵值。 我已經知道使用std::find_if
+ lambda的方法,但是我想知道是否有更好的方法。std :: find_if,std :: binary_function用於按值搜索std :: map
搜索後,我發現this article,我學會了如何使用`std :: binary_function'。 使用這兩種方法,我已經檢查'經過時間'。 這是我的代碼。
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;
}
在我的機器,方法1總是快於方法2。 這是測試結果控制檯。
所以,我的問題是,
- 在我的情況(我的意思是通過搜索值映射),
find_if
+拉姆達是最好的方式? (遺憾的是,我無法使用增強庫。) - 當我使用
std::binary_function
? - 我知道在C++ 11中,`std :: binary_function'已被棄用。我能知道原因嗎?
謝謝您的時間查看此主題並嘗試提供幫助。
該和std :: bind2nd被棄用的原因是我們現在有'std :: function'和'std :: bind'的事實。 – chris
你可以使用C++ 11而不是Boost?有趣的...... bimap對你來說是完美的。 –
你有C++ 1y基於'set' /'map'的透明運算符嗎? – Yakk