1

I'm trying to make a vector of pairs of set: vector<pair<set<int>, set<int>>> but I want to use different lambda comparators for the two sets. I tried doing:

#include <bits/stdc++.h>
using namespace std;

int main() {
    auto cmp = [&] (int a, int b) -> bool {
        return a > b;
    };
    auto hi = [&] (int a, int b) -> bool {
        return a < b;
    };
    vector<pair<set<int, decltype(cmp)>, set<int, decltype(hi)>>> lol(cmp, hi);
    return 0;
}

but it gave me this error:

test.cpp:11:75: error: no matching function for call to ‘std::vector<std::pair<std::set<int, main()::<lambda(int, int)> >, std::set<int, main()::<lambda(int, int)> > > >::vector(main()::<lambda(int, int)>&, main()::<lambda(int, int)>&)’
 ype(cmp)>, set<int, decltype(hi)>>> lol(cmp, hi);
                                                ^
compilation terminated due to -Wfatal-errors.

Also, is there any way to initialize the size of the vector as well? Please help.

AndiChin
  • 161
  • 2
  • 6

1 Answers1

2

You are trying to pass your lambdas to the constructor of the outer vector, which has no constructors that take lambdas as input.

You need to pass the lambdas to the std::set constructor instead, which means you need to construct the individual std::set instances (see C++11 std::set lambda comparison function) and then push them into the vector, eg:

#include <vector>
#include <set>
#include <utility>
using namespace std;

auto cmp = [] (int a, int b) -> bool {
    return a > b;
};

auto hi = [] (int a, int b) -> bool {
    return a < b;
};

using set_cmp = set<int, decltype(cmp)>;
using set_hi = set<int, decltype(hi)>;
using set_pair = pair<set_cmp, set_hi>;

int main()
{
    vector<set_pair> lol;
    ...
    lol.push_back(make_pair(set_cmp(cmp), set_hi(hi)));
    ...
    return 0;
}

This means you would not be able to pre-size the vector, since it would need to be able to default-construct the set objects, thus you couldn't pass your lambdas to them. If you want that, use stateless functors instead:

#include <vector>
#include <set>
#include <utility>
using namespace std;

struct cmp {
    bool operator()(int a, int b) const {
        return a > b;
    }
};

struct hi {
    bool operator()(int a, int b) const {
        return a < b;
    }
};

using set_cmp = set<int, cmp>;
using set_hi = set<int, hi>;
using set_pair = pair<set_cmp, set_hi>;

int main()
{
    vector<set_pair> lol(...desired size...);
    ...
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770