Daniel
Daniel

Reputation: 6775

Container of sets using non-default comparison predicate

I would like to create a std::map<T1, std::set<T2> > where the sets use a non-default comparator. For example, if I were declaring the set on its own, I would declare it as:

std::set<int,bool(*)(int,int)> s (fn_pt);

where fn_pt is a function pointer. In my example, when I add a new key to the std::map, I would like the set to be constructed with that non-default comparator. Is such a thing possible?

To further complicate things, my compiler does not support C++11, so I can only accept a solution that does not require C++11; however, if there is a C++11 way of doing this, I would be interested in seeing that as well.

Upvotes: 1

Views: 2340

Answers (3)

edflanders
edflanders

Reputation: 223

I might be misunderstanding the question, but you can just add keys the normal way, and construct the sets any way you want:

bool Cmp(int, int);
typedef std::set<int,bool(*)(int,int)> MySet;
typedef std::map<int, MySet> MyMap;
...
MyMap m;
m[1] = MySet(Cmp);

Upvotes: 0

luk32
luk32

Reputation: 16090

Not sure why haven't you tried expanding your stub into a full example:

#include <iostream>
#include <set>
#include <map>

typedef std::set<int,bool(*)(int,int)> Set;
typedef std::map<std::string, Set> Map;

bool f(int a, int b){ return a<b;}
bool g(int a, int b){ return a>b;}

int main() {
Map m;
m["f"] = Set(&f);
m["g"] = Set(&g);
for(int i = -5; i < 5; ++i) {
    m["f"].insert(i);
    m["g"].insert(i);
}
for(Set::iterator i = m["f"].begin(); i != m["f"].end(); ++i){std::cout << *i << " ";}
std::cout << "\n";
for(Set::iterator i = m["g"].begin(); i != m["g"].end(); ++i){std::cout << *i << " ";}
std::cout << "\n";
return 0;
}

Output:

-5 -4 -3 -2 -1 0 1 2 3 4
4 3 2 1 0 -1 -2 -3 -4 -5 

Live: http://ideone.com/D2qIHO

I see absolutely no problem in making a map of sets with custom comparers.

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 181047

Since you can use a functor then you should be able to use:

struct Compare
{
    bool operator () (int lhs, int rhs) { return lhs - 10 < rhs; }
};


int main()
{
    std::map<int, std::set<int, Compare> > data;
}

Each new set created in the map would be default constructed with the type specified in the template parameters.

Upvotes: 3

Related Questions