Originally Posted by
anon
map already defines operator<, so struct lpt_key is not strictly necessary.
It is also probably a bit unsafe to just dereference the result of map::find directly, unless you know for sure that this key exists ... in which case you might just as well use map's operator[].
Since I hardcoded this small "application" to add my value to '_map', and since it was only a demonstration of using std::pair as a key in a std::map I didn't see any reason to check if it was really added or not.
Also, just because map have the operator< defined doesn't say that it will treat our key-value the way we want to. Code below as an example:
Code:
#include <iostream>
#include <cstring>
#include <map>
struct ltcstring {
bool operator() (const char *user1, const char *user2) const
{
return strcmp(user1, user2) < 0;
}
};
int
main (int argc, char **argv)
{
const char *user1 = "edoceo";
const char *user2 = "anon";
const char *user3 = "dpp";
std::map<const char *, unsigned short> table1;
std::map<const char *, unsigned short, ltcstring> table2;
std::map<const char *, unsigned short>::iterator it;
/* insert things to table1 */
table1.insert (std::pair<const char *, unsigned short> (user1, 13));
table1.insert (std::pair<const char *, unsigned short> (user2, 2393));
table1.insert (std::pair<const char *, unsigned short> (user3, 82));
/* insert things to table2 */
table2.insert (std::pair<const char *, unsigned short> (user1, 13));
table2.insert (std::pair<const char *, unsigned short> (user2, 2393));
table2.insert (std::pair<const char *, unsigned short> (user3, 82));
std::cout << "Printing std::map<..> table1:" << std::endl;
for(it = table1.begin (); it != table1.end (); it++) {
std::cout << " " << it->first << std::endl;
}
std::cout << std::endl << "Printing std::map<..> table2:" << std::endl;
for(it = table2.begin (); it != table2.end (); it++) {
std::cout << " " << it->first << std::endl;
}
return 0;
}
output:
Code:
Printing std::map<..> table1:
edoceo
anon
dpp
Printing std::map<..> table2:
anon
dpp
edoceo
The reason for this is that std::map's operator< will treat our keys as numeric values, and therfor compare the address where our pointers are pointing. But we want to sort them alphabetically - and therefor we should write our own operator< for this.
It is only proper to use std::less when dealing with numeric values, imo.
Originally Posted by
cpjust
What about using a std::map< char, std::map< char, std::string > >
I believe that should let you use it as m['a']['b'] = "A & B";
Then you don't need to worry about an operator< or creating a new struct or std:: pair...
That is a pretty clean solution, codewise, but in memory it will be both slower and take up more space.
And as 'anon' wrote, you shouldn't (in a real-life scenario) be sure that a key exists when using map.find() or the operator[] - what if memory runs out while trying to add a pair?