Page 1 of 1
C++ string map ordering
Posted: Fri Jul 27, 2007 4:25 am
by Neo
I have a map<string, function> that maps command names to functions that need to be called on invocation of that function.
This has around 100 commands at present. The commands were inserted using make_pair() and when I print them out they are displayed in alphabetical order with the commands that have capitalised starting characters. E.g.
A
B
a
b
I was wondering if there is any simple way (during insert or displaying) that I can get these command names to be displayed with the capitalised starting characters ignored. E.g.
A
a
B
b
TIA
Posted: Fri Jul 27, 2007 4:37 am
by AJ
Hi,
Can't you just do your comparison with toupper or tolower? e.g. instead of doing your sort by:
do:
Code: Select all
if(toupper(char1)<toupper(char2)) do_swap_here;
You could also quite easily implement a version of strcmp which uses toupper when comparing each character.
Cheers,
Adam
Posted: Fri Jul 27, 2007 6:27 am
by Candy
use an std::string that makes character-insensitive compares (IE, with std::basic_string<char, my_char_traits<char> > ?)
Posted: Fri Jul 27, 2007 7:03 am
by urxae
Candy wrote:use an std::string that makes character-insensitive compares (IE, with std::basic_string<char, my_char_traits<char> > ?)
Alternatively, supply a case-insensitive variant of std::less as the comparator function/functor (the third argument to std::map, defaults to std::less<KeyType>). That would allow "normal" strings to be used.
Posted: Sun Jul 29, 2007 1:35 am
by Neo
Thanks for the help folks.
I tried both and found adding of the string compare easier than using a customized string class for the task I needed.
Posted: Tue Aug 07, 2007 12:06 am
by Neo
I was just wondering when the comparator function in map is called?
I think it should be only when we insert anything into the map? or are there any cases where this is called?
Posted: Tue Aug 28, 2007 3:15 pm
by bregma
Neo wrote:I was just wondering when the comparator function in map is called?
I think it should be only when we insert anything into the map? or are there any cases where this is called?
The comparisone function would be called whenever you traverse the tree using a key. That would include insertions, removals, or finds.
--smw