2013-10-21 59 views
1

我需要帮助能够在运行时定义自定义std :: set比较器。我知道如何定义一个固定值的基本比较器。我真的被困在如何在运行时做到这一点。如果有帮助,我正在运行Visual Studio 2010。在运行时定义自定义比较器std :: set

下面是我的代码:

#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; 
} 

谢谢。

回答

6

比较被作为参数传递给集合构造:

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

谢谢。我一直在阅读std :: set文档,并且这些时候我的眼前的答案是正确的。不知何故,我的大脑没有把它拿起来。 – nightcom26