C++如何在地图中定义自定义键(与类似问题有点不同)?

C++ how to define custom key in map(It's a little different from similar problems)?

我想定义一个像这样的地图:

#include<map>
struct key{
    vector<int> start_idx;
    vector<int> len;
};

map<key, int> m;

看了其他题,发现比较函数也可以这样写

struct Class1Compare
{
   bool operator() (const key1& lhs, const key2& rhs) const
   {
       .....
   }
};

事实上,start_idx表示文件中的起始索引,len表示长度,所以我需要在比较函数中使用其他参数,如:

bool operator() (const key1& lhs, const key2& rhs) const
{
    ... //in this field, i can use (char *file).
}

而且char *file可能不是全局的,因为我用的是多线程,也就是说在不同的线程中,char *file是不一样的。

你的比较器中可以有数据成员。

struct Class1Compare
{
    bool operator() (const key1& lhs, const key2& rhs) const
    {
        // uses lhs, rhs and file
    }
    char * file;
};

您的地图将需要非默认构造 Class1Compare

char * file = /* some value */
map<key, int, Class1Compare> m({ file });
key k = /* key's data relating to file */
m[k] = 42;