如何为地图创建自己的比较器?

Xit*_*rum 72 c++ stl stdmap

typedef map<string, string> myMap;
Run Code Online (Sandbox Code Playgroud)

插入新对时myMap,它将使用键string通过自己的字符串比较器进行比较.是否可以覆盖该比较器?例如,我想比较密钥string的长度,而不是字母表.或者还有其他方法可以对地图进行排序吗?

Geo*_*che 123

std::map最多需要四个模板类型参数,第三个是比较器.例如:

struct cmpByStringLength {
    bool operator()(const std::string& a, const std::string& b) const {
        return a.length() < b.length();
    }
};

// ...
std::map<std::string, std::string, cmpByStringLength> myMap;
Run Code Online (Sandbox Code Playgroud)

或者,您也可以将比较器传递给maps构造函数.

但请注意,按长度比较时,地图中每个长度只能有一个字符串作为键.

  • 请注意,如果我们要包含重复的键,则可以使用多图 (3认同)
  • @GeorgFritzsche:这不适用于将比较器传递给构造函数,因为构造函数参数必须是比较器类型的实例,并且 `cmpByStringLength` 不是 `std::less&lt;std::string&gt;` 的实例. 对于可以在构造函数中设置任何比较器的通用映射,您需要类似`std::map&lt;std::string, std::string, std::function&lt;bool(const std::string &amp;, const std ::string &amp;)&gt;&gt; myMap(cmpByStringLength);` (2认同)

Joh*_*ing 12

是的,第3个模板参数on map指定比较器,它是二进制谓词.例:

struct ByLength : public std::binary_function<string, string, bool>
{
    bool operator()(const string& lhs, const string& rhs) const
    {
        return lhs.length() < rhs.length();
    }
};

int main()
{
    typedef map<string, string, ByLength> lenmap;
    lenmap mymap;

    mymap["one"] = "one";
    mymap["a"] = "a";
    mymap["fewbahr"] = "foobar";

    for( lenmap::const_iterator it = mymap.begin(), end = mymap.end(); it != end; ++it )
        cout << it->first << "\n";
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么派生自`std :: binary_function`?需要它吗? (11认同)
  • 在c ++ 17中删除了`std :: binary_function`,所以这个答案可能会使用更新. (11认同)

hon*_*onk 11

C++ 11开始,您还可以使用lambda表达式而不是定义比较器结构:

auto comp = [](const string& a, const string& b) { return a.length() < b.length(); };
map<string, string, decltype(comp)> my_map(comp);

my_map["1"]      = "a";
my_map["three"]  = "b";
my_map["two"]    = "c";
my_map["fouuur"] = "d";

for(auto const &kv : my_map)
    cout << kv.first << endl;
Run Code Online (Sandbox Code Playgroud)

输出:

1

三个
fouuur

我想重复Georg的答案的最后一点:当按长度比较时,你只能在地图中将每个长度的一个字符串作为键.

Ideone上的代码