C++ string map ordering

Programming, for all ages and all languages.
Post Reply
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

C++ string map ordering

Post 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
Only Human
User avatar
AJ
Member
Member
Posts: 2646
Joined: Sun Oct 22, 2006 7:01 am
Location: Devon, UK
Contact:

Post by AJ »

Hi,

Can't you just do your comparison with toupper or tolower? e.g. instead of doing your sort by:

Code: Select all

if (char1<char2) do_swap_here;
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
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Post by Candy »

use an std::string that makes character-insensitive compares (IE, with std::basic_string<char, my_char_traits<char> > ?)
urxae
Member
Member
Posts: 149
Joined: Sun Jul 30, 2006 8:16 am
Location: The Netherlands

Post 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.
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

Post 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.
Only Human
User avatar
Neo
Member
Member
Posts: 842
Joined: Wed Oct 18, 2006 9:01 am

Post 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?
Only Human
bregma
Member
Member
Posts: 25
Joined: Tue Oct 26, 2004 11:00 pm
Location: the back woods
Contact:

Post 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
Post Reply