can we use lambda to initialize set/map container?

1
2
3
4
5
6
7
8
9
//neccessary headfiles are included
  int main(){
    auto f=[](int x,int y){return x>y;};   
    auto f2=&f; 
    set<int,decltype(f2)> tree(f2);
    for(auto elem:tree){cout<<elem<<endl;}
    
    return 0;
}

what is the wrong with my code?
can we use lambda to initialize set/map?If yes,how to?If not,why can we do that when initializing set by function pointer is ok?
I don't think you can use a lambda for the set sort comparison (?). This compiles OK:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <set>
#include <iostream>
using namespace std;

struct f2 {
	bool operator()(int x, int y) const { return x > y; }
};

int main() {
	set<int, f2> tree {3,4,5,6,7};

	for (auto elem : tree) { cout << elem << '\n'; }
}



7
6
5
4
3

Something like...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <set>

int main()
{
    auto comp = [](int x, int y) { return x > y; };
    auto tree = std::set<int, decltype(comp)>(comp);

    tree.insert(4);
    tree.insert(10);
    tree.insert(6); 
    tree.insert(1);

    for (auto elem : tree)
    {
        std::cout << elem << ' ';
    }
}
Last edited on
OK :) :)
> neccessary headfiles are included
Why not paste the necessary #includes yourself so that others can simply run your code without modification?
Topic archived. No new replies allowed.