编写自定义比较功能以停止键排序时,无法在stl映射中查找 [英] Find in a stl map doesn't work when a custom compare function is written which stops keys from sorting
问题描述
class compare
{
public:
bool operator()(const int x,const int y) const
{
if(x-y == 0)
return false;
else
return true;
}
};
int main()
{
std::map<char,int,compare> mymap;
//Add data into map
mymap.insert ( std::pair<char,int>('f',100) );
mymap.insert ( std::pair<char,int>('a',100) );
mymap.insert ( std::pair<char,int>('k',100) );
mymap.insert ( std::pair<char,int>('z',200) );
//try to find a key in map
std::map<char,int,compare>::iterator l_pos = mymap.begin();
l_pos = mymap.find('z');
if(l_pos != mymap.end())
{
printf("\nfound = %c\n",l_pos->first);
}
else
{
printf("Not found = %c\n",l_pos->first);
}
}
结果:
Not found =
但是,如果我显示地图,我可以看到其内容.mymap包含:f => 100 a => 100 k => 100 z => 20
But if I display the map I can see the contents. mymap contains: f => 100 a => 100 k => 100 z => 20
在编写自定义比较函数以停止键排序时,无法在stl映射中进行查找.查找失败.有没有办法解决这个问题?查找不返回任何数据.我知道stl映射不用于此目的.但是有办法解决这个问题吗?比较功能停止排序.条目以相反的顺序存储.当我使用for循环遍历映射时,我可以看到所有值.只是find命令不起作用.
Find in a stl map doesn't work when a custom compare function is written which stops keys from sorting. The Find fails. Is there a way to fix this? Find doesn't return any data. I know stl maps are not for this purpose. But is there way to fix this? The Compare function stops sorting. The entries are stored in reverse order. When I use a for loop to iterate through the map I can see all the values. It is only the find command which is not working.
推荐答案
您的比较
函子已损坏.
map
使用比较器来实现严格的弱排序.
A map
uses a comparator to implement strict weak ordering.
每个关联容器都在Key和一个排序参数上进行了参数化关系比较,它导致严格的弱排序(25.3)键的元素.
Each associative container is parameterized on Key and an ordering relation Compare that induces a strict weak ordering (25.3) on elements of Key.
您的 compare()
函数不会执行此操作,因此会导致未定义行为.不是 map
在这里坏了,但是您对它的使用使得除了重新实现 compare()
从而导致严格的弱化之外,没有其他方法可以修复"此问题.在元素上排序,或使用 map
以外的容器.
Your compare()
function doesn't do this, and so results in Undefined Behavior. It isn't map
that's broken here, but your use of it so there is no way to "fix" this other than reimplementing compare()
so as to induce strict weak ordering on the elements, or use a container other than map
.
这篇关于编写自定义比较功能以停止键排序时,无法在stl映射中查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!