简体   繁体   中英

Entries(<key,values>) are not entered in a map

I want save values in a std::map if an hash function return a value that isn't already contained in the map. The data structure is:

std::map<uint8_t* , MyObject* , lex_compare> mymap;

where uint8_t* point to a C-style array of 128 bit ( uint8_t hash_value[16] ) that contain the hash function applied to a field of class MyObject . I use lex_compare for a personalized comparison:

struct lex_compare {
bool operator() (const uint8_t *hash1, const uint8_t *hash2) const {
    /*for(int i=0 ; i<16 ; i++)
             {
                 cout<<(unsigned int)hash1[i]<<" ";
             }
             cout<<endl<<endl;
             for(int i=0 ; i<16 ; i++)
             {
                 cout<<(unsigned int)hash2[i]<<" ";
             }
    int m=memcmp(hash2,hash1,16);
    cout<<"m is è"<<m<<endl;*/
    return (memcmp(hash2,hash1,16)<0); //compare 16 byte.
    }
};

To ensure insertion only if an hash value is not already contained in the map I use:

while(mymap.size()<R)
{
myObject *temp_o  = new myObject(parameters);
uint8_t hash_result = my_hash_function(myObject->return_field()) // return_field is a specific field of myObject 
mymap.insert(make_pair(hash_result,temp_o));
}

But only one element is inserted in mymap , thus I go in endless loop. Why? I can not explain it. Look at lex_compare I saw that this function return always zero value (because is called on 2 equals elements). May be is a trivial problem, but I'm not able to see it.

EDIT: I correct problem in comparison function. But later correction main problem remains

Short answer: try with

return (memcmp(hash2,hash1,16) > 0);

Long answer: memcpy() return a negative value if the first argument is lower than the second, zero if they are equal and a positive value if the first value is greater than the second.

But your operator() return a boolean. So negative and positive value are converted in true and zero is converted in false . So, according your operator() , hash1 is lower that hash2 if they are different. And the bad part is that, if hash1 and hash2 are different, hash1 result lower than hash2 and hash2 result lower than hash1 . This give to the program an undefined behavior.

Solution: modify the return instruction or in this way

return (memcmp(hash2,hash1,16) > 0);

or as follows

return (memcmp(hash2,hash1,16) < 0);

to be sure that true == operator()(hash1, hash2) imply that false == operator()(hash2, hash1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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