how to use a different type to find value in std::set

I have a struct like:
struct point{
int f;
int b;
point(){}
point(int u, int v){
f = u; b = v;
}
bool operator<(const point & foo) const {
return this->f < foo.f;
}
bool operator<(int foo) const {
return this->f < foo;
}
};
how can I use int as parameter instead of using point?
set<point> s;
-> s.find(3);
Maybe just:

1
2
3
4
5
// In point:
    point(int u, int v=0) : f(u), b(v) {}

// Just make a point and pass that
s.find(point(3));

You can use a transparent comparator, such as std::less<>:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <set>
#include <functional>

struct point{
    int f;
    int b;
    
    point() = default;
    point(int u, int v) : f(u), b(v) {}
    
    friend bool operator<(const point& lhs, const point& rhs) {
        return lhs.f < rhs.f;
    }
    friend bool operator<(const point& lhs, int rhs) {
        return lhs.f < rhs;
    }
    friend bool operator<(int lhs, const point& rhs) {
        return lhs < rhs.f;
    }
};

int main() {
    std::set<point, std::less<>> s = { point{1, 2}, point{3, 4}, point{5, 6} };
    std::cout << s.find(3)->b;
}

http://coliru.stacked-crooked.com/a/fda90f626fadbbf1
transparent comparator is not worked in my project, I'm still using C++03...
error code C2976.

I was confused, if I have a key_type value with the key I need(such as point(3,4)), why I need to find it in std::set?
Last edited on
I was confused, if I have a key_type value with the key I need(such as point(3,4)), why I need to find it in std::set?

One can ask: Does set X contain value Y? (Then again, set::count() gives that result too.)


Note also that your partial match returns at most one point with set::find(), while the set may contain multiple unique points that all have point::f == 3. Surely you want them all?

Perhaps with lower_bound and upper_bound http://www.cplusplus.com/reference/set/set/lower_bound/
1
2
3
4
5
6
7
auto itlow = s.lower_bound( point(3, std::numeric_limits<int>::min() ) );
auto itup  = s.upper_bound( point(4, std::numeric_limits<int>::min() ) );
std::cout << "Points with f==3:\n";
while ( itlow != itup ) {
  std::cout << itlow->f << ' ' << itlow->b << '\n';
  ++itlow;
}
Topic archived. No new replies allowed.