I'm trying to pass a lambda as a sorting criterion to a set of indices of type int. I have used an unordered_map to map the indices to their values and passed it by value to the lambda which takes two indices and returns bool.
The code compiles but I'm getting "bad function call" error at run-time.
I've used std::function<> type wrapper to declare the lambda instead of using decltype() which was giving an error.
Code:
#include <iostream>
#include <unordered_map>
#include <functional>
#include <set>
#include <vector>
using namespace std;
int main()
{
int T;
cin >> T;
while (T--)
{
int N;
cin >> N;
unordered_map<int, int> M;
function<bool(int, int)> l = [M](int i1, int i2)->bool { return M.at(i1) > M.at(i2); };
set<int, function<bool(int, int)>> S;
for (int i = 1; i <= N; ++i)
{
int p;
cin >> p;
M[i] = p;
S.insert(i);
}
vector<vector<int>> Adj(N + 1);
for (int i = 1; i <= N - 1; ++i)
{
int u, v;
cin >> u >> v;
Adj[u].push_back(v);
Adj[v].push_back(u);
}
int maximum = 0;
for (int i = 1; i <= N; ++i)
{
S.erase(i);
for (int e : Adj[i])
S.erase(e);
cout << *S.cbegin() << ' ';
for (int e : Adj[i])
S.insert(e);
S.insert(i);
}
cout << endl;
}
}
Input:
1
6
5 10 15 20 25 30
1 3
2 3
3 4
4 5
4 6
I have this code inside a try-catch block and it's printing "bad function call" when I enter the second value (10 in the input)
std::setby doing this:set<int, function<bool(int, int)>> S;? If so, I don't think the syntax is correct. - vahancho[M]"captures by copy", meaning that changes to theMin the containing function won't have any effect on theMused inside the lambda. It looks like you want[&M]to "capture by reference". (But then make sure no copy of thatstd::functionlives longer thanM!) - aschepler