I have been having this problem for awhile with my code, looking for my mistake I can't see it. I have a map, map I am mapping keywords to the values.
My problem is sometimes when inserting keyword = "Blue" the value is inserting into the Key for "Red".
So instead of,
Key: Red, Value: obj1, obj2
Key: Blue, Value: obj3, obj4
I get,
Key: Red, Value: obj1, obj2, obj4 (obj4 should be keyed to Blue)
Key: Blue, Value: obj3
Not sure what it can be since the same version of the code works for other maps that I have, they just don't have as many Keys.
addKeywordsForObject(const Object* const object, int nKeywords, ...)
{
va_list keywords;
char *keyword;
va_start(keywords, nKeywords);
for (int i = 0; i < nKeywords; i++) {
keyword = va_arg(keywords, char*);
if(objectToKeywordMap.find(keyword) == objectToKeywordMap.end()) {
keywordObject = new ObjectSet();
keywordObject->insert(const_cast<Object* const>(object));
objectToKeywordMap.emplace(StringToObjectSetMap::value_type(keyword,keywordObject));
}
else {
keywordObject->insert(const_cast<Object* const>(object));
objectToKeywordMap.emplace(StringToObjectSetMap::value_type(keyword,keywordObject));
}
}
va_end(keywords);
}
most probably the problem is that you haven't define your sort function for the key type
that that your map has. You need to 'tell' the map how to sort the index-type
For example:
struct sortKey{
bool operator()(key_type const& k1, key_type const& k2){
//define your sort criteria here
}
}
std::map<key_type,value_type,sortKey> the_map;
Please comment if you think there is something else that you are missing.
I see no declaration for keywordObject
, so I shall assume it's a global. The case of adding a new object to a keyword which is already present is dealt with in the else
. What is the value of keywordObject
in this case? Who sets it?
There are a number of other problems with this code, some mentioned in other answers and comments.
addKeywordsForObject
char*
as a map key which requires special handling (not clear, because you haven't shown the declaration of StringToObjectSetMap
)
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.