0

I want to define a map like:

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

map<key, int> m;

I looked at other questions and found that I could write the comparison function like this

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

In fact, start_idx means a start index in a file, len means length, so I need to use other parameter in the comparsion function like:

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

and char *file may not be global, because I use multi-thread which means in different thread, char *file is different.

Li.sili
  • 39
  • 3
  • Do you want to read a file inside a comparator? It's hardly a good idea. – Evg Jan 05 '22 at 08:54
  • 2
    This looks like a [xy problem](https://xyproblem.info/), perhaps also specify what your goal is. That way you can find the best solution. – Robin Dillen Jan 05 '22 at 08:56
  • Your comparator can keep a reference to the file. But then everyone of your `map` instances can be different when they reference different files. – j6t Jan 05 '22 at 09:20
  • Does this answer your question? [How can I create my own comparator for a map?](https://stackoverflow.com/questions/5733254/how-can-i-create-my-own-comparator-for-a-map) – S4eed3sm Jan 05 '22 at 09:23
  • I am so sorry for my poor English ability to describe the problem and thanks for following my question. The answer below solved my problem. – Li.sili Jan 10 '22 at 06:15

1 Answers1

3

You can have data members in you comparer.

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

Your map will require a non-default constructed Class1Compare.

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