我无法访问 BOOST 或 STL;我的结构和 map 看起来类似于以下伪装:
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 的所有情况。我不太确定,但我想我需要在我的结构中创建谓词对于“发现”。想法?
最佳答案
operator<
这就是find
所需要的或其他任何东西。但是,您的实现有一个错误。它返回 true
如果操作数相等。
find
和其他标准库组件使用 a == b iff ! (a < b) && ! (b < a)
的假设, 所以如果 a
和 b
相等,<
必须是 false
对于 find
去工作。
else if (b == smk.b)
{
return false; // was true
}
关于c++ - 在 C++ 中使用 .find() 和 struct 作为映射中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5655179/