简体   繁体   中英

Define custom comparator at run time for std::set

I need help on being able to define a custom std::set comparator at run time. I know how to define a basic comparator with fixed value. I am really stuck on how to do it at run time. I am running Visual Studio 2010, if that helps.

Below is my code:

#include <set>

struct CustomComp
{
    CustomComp():m_tolerance(0.1){}

    //Always assume tolerance >= 0.0
    CustomComp(double const &tolerance):m_tolerance(tolerance){}

    /*Only return true when the two number are sufficiently apart from each other*/
    bool operator()(double const &n1, double const &n2)
    {
        double diff = n1 - n2;
        if(diff < 0.0 && std::abs(diff) > m_tolerance) return true;
        if(diff > 0.0 && std::abs(diff) > m_tolerance) return false;

        return false;
    }
private:
    double m_tolerance;
};


int main(int argc, char **argv)
{
    /*This works */
    std::set<double, CustomComp> aaa;
    aaa.insert(0.0);
    aaa.insert(0.2);
    aaa.insert(0.3);
    aaa.insert(10.0);

    /*What I really want*/
    double tol = GetToleranceFromUser();
    std::set<double, CustomComp(tol)> bbb;

        return 0;
}

Thank you.

比较器作为参数传递给set构造函数:

std::set<double, CustomComp> bbb(CustomComp(tol));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM