简体   繁体   English

STL map.find返回不正确的元素

[英]STL map.find returns incorrect element

I have the following, which seems to be returning the first ie 0th node in the map. 我有以下,似乎返回地图中的第一个即第0个节点。 I cant figure out whats wrong with this code. 我无法弄清楚这段代码有什么问题。

The map.find always returns the first (0th) element. map.find始终返回第一个(第0个)元素。 No matter what the inputs are constructed in the 'insert' call. 无论在'insert'调用中构造什么输入。

I am somewhat new to STL , so any help would be appreciated. 我对STL有些新意,所以任何帮助都会受到赞赏。 Is there something that I am missing here ? 这里有什么我想念的吗?

class numbers{
public :
    unsigned int data;
    numbers(unsigned int value)    {
        data=value;
    }
};
bool operator<(numbers a, numbers b){
    return (a.data<b.data)?a.data:b.data;
}

class names{
public:
    string s;
    names(int value)    {
        char arr[10];
        itoa(value, arr, 10);
        s=arr;
    }
    void print(){cout<<s;}
};

void main(){
    map<numbers, names> bigmap;
    for(int i=0;i<1000;i++)
        bigmap.insert(pair<numbers,names>( numbers(i), names(i)));
    cout<<"Inserted!";
    map<numbers, names>::iterator p;
    p=bigmap.find(numbers(10));
    p->second.print();//output is always 0
    getchar();
    //Large Lookup test
}

Is there something that I am missing here ? 这里有什么我想念的吗? DI need to preallocate the objects and then supply to the insert operation. DI需要预先分配对象然后提供给插入操作。 I dont think STL maps require them to be preallocated. 我不认为STL地图要求他们预先分配。 Thanks, any help on that front would be greatly appreciated. 谢谢,在这方面的任何帮助将不胜感激。

Your comparison operator is wrong. 您的比较运算符是错误的。 Your implementation will always return true unless a is 0 and is less than the RHS, or b is 0 and is greater than or equal to the LHS. 除非a0且小于RHS,或者b0且大于或等于LHS,否则您的实现将始终返回true Just return the result of the comparison. 只需返回比较结果即可。

bool operator<(numbers a, numbers b){
    return (a.data<b.data);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM