2013-11-21 4 views
0

구조체 one의 객체를 맵에 고유 키로 삽입하려고합니다. 그래서 나는 operator() 함수를 작성했지만 find 요소가 맵에 존재하지 않습니다.찾기 기능이 작동하지 않습니다.

#include <iostream> 
#include<map> 
#include <stdio.h> 
#include <string.h> 
#include <math.h> 
using namespace std; 
struct one 
{ 
    char* name_; 
    double accuracy_; 
    one(char* name, double accuracy) 
     { 
       name_ = name; 
       accuracy_ = accuracy; 
     } 
}; 
const float Precision = 0.000001; 
struct CompLess:public std::binary_function<const one, const one, bool>{ 
    bool operator()(const one p1, const one p2) const 
    { 
     if (strcmp(p1.name_, p2.name_)<0) 
     { 
      return true; 
     } 
     if(((p1.accuracy_) - (p2.accuracy_)) < Precision and 
      fabs((p1.accuracy_) - (p2.accuracy_))> Precision) 
     { 
      return true; 
     } 
     return false; 
    } 
}; 

typedef map<const one,int,CompLess> Map; 

int main() 
{ 
    one first("box",30.97); 
    one first1("war",20.97); 
    Map a; 
    a.insert(pair<one,int>(first,1)); 
    a.insert(pair<one,int>(first1,11)); 
    if(a.find(first1) == a.end()) 
    { 
     cout<<"Not found"<<endl; 
    } 
    else 
    { 
     cout<<"Found"<<endl; 
    } 
    return 0; 
} 

답변

0

비교 클래스는 엄격한 주문을 유도하지 않습니다. 당신이 그것을 변경해야합니다 :

bool operator()(const one p1, const one p2) const 
{ 
    if (strcmp(p1.name_, p2.name_) == 0) 
    { 
     if (((p1.accuracy_) - (p2.accuracy_)) < Precision and 
      fabs((p1.accuracy_) - (p2.accuracy_))> Precision) 
     { 
      return true; 
     } 
    } 

    return false; 
} 

버전 first1에서였다 strcmp("war", "box") > 0 (첫 번째 조건은 false입니다) 미만 first120.97 < 30.97 (두 번째 조건은 true입니다)하지만, 같은 시간에 first이었다 미만 first 때문에, strcmp("box", "war") < 0 (첫 번째 조건은 true)입니다. 두 번째 차원은 첫 번째 차원이 동일한 경우에만 비교해야합니다. less 비교의 좋은 경험 법칙입니다.

+0

@ BartoszKP 세 가지 변수가있는 경우 어떻게해야합니까? – sawaan

+0

@ swanan 같은 방식으로, 계층 적으로. 'i' k에 대한 모든 i 번째 변수의 모든 비교가 동등한 결과를 얻은 경우에만'k' 변수를 검사합니다. 다른 말로하면 : 변수'k'에 대한 비교가 부등식 ('x y'와 상관 없다면)은 결과가이 변수에만 기반을 두어야하며, 변수 i는'i> k'를 보지 않아야합니다. – BartoszKP