使用std::map
' 从外部定义比较器的能力std::map
,如下所示:
#include <iostream>
#include <map>
#include <string>
#include <string.h>
#include <functional>
using namespace std;
// Define comparator functor:
struct functor_test
{
bool operator()(string const & lhs, string const & rhs)
{
return strncmp(lhs.c_str(), rhs.c_str(), 4) < 0;
}
};
// Define comparator function:
bool function_test(string const & lhs, string const & rhs)
{
return strncmp(lhs.c_str(), rhs.c_str(), 4) < 0;
}
int main() {
// Define comparator lambda:
auto lambda_test = [](string const & lhs, string const & rhs)
{
return strncmp(lhs.c_str(), rhs.c_str(), 4) < 0;
};
// These are all valid ways to declare the key comparitor:
//As a functor:
// map<string, string, functor_test> map;
//As a function using a function reference type:
// map<string, string, bool(&)(string const&, string const&)> map(function_test);
//As a function using a function pointer type:
// map<string, string, bool(*)(string const&, string const&)> map(function_test);
//As a function using a function class type wrapper:
// map<string, string, function<bool(string const&, string const&)>> map(function_test);
//As a predefined lambda:
// map<string, string, decltype(lambda_test)> map(lambda_test);
//As a predefined lambda using a function class type wrapper:
// map<string, string, function<bool(string const&, string const&)>> map(lambda_test);
//As a lambda using a function class type wrapper:
map<string, string, function<bool(string const&, string const&)>> map(
[](string const & lhs, string const & rhs)
{
return strncmp(lhs.c_str(), rhs.c_str(), 4) < 0;
});
map["test"] = "Foo";
map["blah"] = "Drei";
map["fayh"] = "Najh";
std::cout << map.find("test123")->second << endl; // Should output 'Foo'
std::cout << map.find("test_2165")->second << endl; // Should output 'Foo' as well
if (map.find("tes") == map.end())
{
cout << "Not found" << endl;
}// Key not found
std::cout << map.find("fayh_TK_Ka")->second << endl; // 'Najh'
return 0;
}
要使用工作演示,请参见此处:http: //ideone.com/sg4sET
注意:这段代码展示了一堆不同的方法来做同样的事情。只使用你需要的东西。我个人认为最后一个是最简单和最容易阅读的,因为它不会分散代码远离它的使用。