C++ 查找功能不工作
我想在映射中插入structC++ 查找功能不工作,c++,map,find,C++,Map,Find,我想在映射中插入structone的对象作为唯一键。所以我编写了operator()函数,但find即使map中存在元素也不起作用 #include <iostream> #include<map> #include <stdio.h> #include <string.h> #include <math.h> using namespace std; struct one { char* name_; double a
one
的对象作为唯一键。所以我编写了operator()
函数,但find
即使map中存在元素也不起作用
#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;
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
结构一
{
字符*名称u;
双精度;
一(字符*名称,双精度)
{
姓名=姓名;
准确度=准确度;
}
};
常数浮点精度=0.000001;
结构完整性:公共标准::二进制函数{
布尔运算符()(常数一p1,常数一p2)常数
{
if(strcmp(p1.name,p2.name)精度)
{
返回true;
}
返回false;
}
};
typedef地图;
int main()
{
第一个(“盒子”,30.97);
一个优先1(“战争”,20.97);
地图a;
a、 插入(一对(第一,1));
a、 插入(对(第一个1,11));
如果(a.find(first1)=a.end())
{
cout您的比较类不会导致严格的排序。您应该将其更改为:
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;
}
bool运算符()(常数一p1,常数一p2)常数
{
if(strcmp(p1.name,p2.name)==0)
{
如果((p1.精度)-(p2.精度)<精度和
晶圆厂((p1.精度)-(p2.精度)->精度)
{
返回true;
}
}
返回false;
}
在您的版本中,first1
小于first
,因为strcmp(“war”、“box”)>0
(第一个条件是false
)和20.97<30.97
(第二个条件是true
),但同时,first
小于first1
,因为strcmp(“box”、“war”)<0
(第一个条件为true
).只有当第一个维度相等时,你才应该比较第二个维度-这是less
比较的经验法则。@BartoszKP如果有三个变量,那么在这种情况下我应该如何处理?@sawaan以同样的方式,分层地进行比较。只有当所有Ik
th变量i
的de>th变量导致相等。换句话说:如果变量k
的比较产生不相等(无论xy
),则结果必须仅基于此变量,而不查看i
k
的变量i
。