I have this multimap built to map the hamming distance of a string to its corresponding string.
Since the hamming distance of two strings could be the same, I want them to be sorted in ascending order. However when I print it out, it is not sorted. The hamdistArray is declared as an unsigned type.
typedef multimap<unsigned, string, less<unsigned> &g开发者_如何学编程t; Check;
Check pairs;
pairs.insert(Check::value_type(hamdistArray[j], d.sortedWordDatabase[j]));
for(Check::const_iterator iter = pairs.begin(); iter != pairs.end(); ++iter)
{
cout << iter->first << '\t' << iter->second<< endl;
}
Elements in a multimap are sorted by the key (in this case the unsigned hamming distance). Elements with the same key are not sorted by the value (in this case the string), they are usually kept in the order in which they were inserted.
This is not possible using std::multimap
, because when keys are compared, it is not known which value they represent.
multimap
only sorts by its key (length) not also by value (string). In this case I suspect your best approach is a std::map<unsigned, std::set<std::string> >
. You could also use a std::set<std::pair<unsigned, std::string> >
but searching would require you to construct dummy pair
s to search on.
The less template function is not necessary since it's the default. Try declaring Check without as:
typedef multimap<unsigned, string> Check;
Edited: The best way to do this is to generate a hash-key as the *key_type* and than the value-type could be a std::pair<unsigned, string>
精彩评论