binary_search



#include <algorithm>
#include <iostream>
#include <vector>
                                                                                                                
using std::vector,
    std::binary_search,
    std::boolalpha,
    std::cerr;
                                        
class Temp{
    public:
        int a, b;
        Temp(int i, int j):a(i), b(j){}
};
bool operator<(const Temp& l, const Temp& r)
{
    if((l.a + l.b) < (r.a + r.b)){
        return true;
    }
    return false;
} 

bool operator==(const Temp& l, const Temp& r)
{
    if((l.a + l.b) == (r.a + r.b)){
        return true;
    }
    return false;
} 
                        
typedef vector<Temp> my_vector;
            
int main(){
    cerr << boolalpha;

    vector l = {1, 5, 16, 22, 32, 44, 49, 61};
    bool found = binary_search(l.begin(), l.end(), 7);
    cerr << "found: " << found << "\n";
    found = binary_search(l.begin(), l.end(), 44);
    cerr << "found: " << found << "\n";


    my_vector a = {Temp(0, 0), Temp(1, 1), Temp(2, 4), Temp(3, 9), Temp(3, 9), Temp(4, 16), Temp(5, 25), Temp(6, 36), Temp(7, 49), Temp(8, 64), Temp(9, 81), Temp(10, 100), Temp(11, 121), Temp(12, 144), Temp(13, 169), Temp(14, 196), Temp(15, 225), Temp(16, 256), Temp(17, 289), Temp(18, 324), Temp(19, 361)};
    sort(a.begin(), a.end());
    found = binary_search(a.begin(), a.end(), Temp(2, 7));
    cerr << "found: " << found << "\n";

    auto test = [] (Temp a, Temp b)->bool{
        if((a.a + a.b) < (b.a + b.b)){
            return true;
        }
        return false;
    };

    found = binary_search(a.begin(), a.end(), Temp(9, 80), test);
    cerr << "found: " << found << "\n";
    return 0;
}      
C++ Examples© 2024 TBD