在C ++中使用.find()和struct作为键 [英] Using .find() with struct as key in map in C++
问题描述
我无权使用BOOST或STL;我的结构和映射类似于以下伪指令:
I do not have access to BOOST or STL; my struct and map looks similar to the following psuedo:
struct s_map_key{
int a;
int b;
bool operator<(const s_map_key& smk) const
{
if (a < smk.a)
{
return true;
} else if (a == smk.a)
{
if (b < smk.b)
{
return true;
}
else if (b == smk.b)
{
return true;
}
}
return false;
}
};
int main(int argc, char* argv[])
{
std::multimap<s_map_key, std::string> myMap;
for(int i = 0; i <10; i++)
{
s_map_key smk;
smk.a = i;
smk.b = 2;
myMap.insert(std::make_pair(smk, "test"));
}
s_map_key smk;
smk.a = 3;
std::multimap<s_map_key, std::string>::iterator x = myMap.find(smk);
if(x != myMap.end())
{
std::cout << x->first.a <<std::endl;
std::cout << x->first.b <<std::endl;
}
return 0;
}
我想做的是在我的多重地图中搜索A = 2,B = 2或A&的所有情况. B =2.我不确定,但是,我认为我需要在我的结构中创建谓词以查找".想法?
What I am trying to do is search my multimap for all cases where A = 2, B = 2, or A & B = 2. I am not exactly sure but, I think i need to create the predicates in my struct for "finding". Ideas?
推荐答案
operator<
是find
或其他所有功能的全部.但是,您的实现有一个错误.如果操作数相等,则返回true
.
operator<
is all you need for find
or anything else. However, your implementation has a bug. It returns true
if the operands are equal.
find
和其他标准库组件使用a == b iff ! (a < b) && ! (b < a)
的假设,因此,如果a
和b
相等,则<
必须为false
才能使find
正常工作.
find
and other Standard Library components use the assumption that a == b iff ! (a < b) && ! (b < a)
, so if a
and b
are equal, <
must be false
for find
to work.
else if (b == smk.b)
{
return false; // was true
}
这篇关于在C ++中使用.find()和struct作为键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!