Cant use command line argument as map key

Hi.

I have problem with my program. If I use numbers["one"] directly then it prints me 1 but when I use numbers[argv[1]] I get 0. Why is it so? It's very strange because cout << "'" << argv[1] << "'" << endl; prints 'one' which means that it actually receives the the argument but for some reason I can use it as map key.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <map>
using namespace std;

int main(int argc, char *argv[]) {


    map<char*, int> numbers;
    numbers["one"] = 1;
    numbers["two"] = 2;
    numbers["three"] = 3;

    if(argc == 2){
        cout << "'" << argv[1] << "'" << endl;
        cout << numbers[argv[1]] << endl;

    }else{
        cout << numbers["one"] << endl;
    }

    return 0;
}
Last edited on
Your map key is a char-pointer. A char-pointer is a single number, representing a memory address. It is a char pointer that happens to point at the string "one" that you created in your code, but that's irrelevant. Your key is a single number.

argv[1] is a char-pointer pointing at some completely different piece of memory. What's in the memory it points to is irrelevant. Your key is not a string. Your key is a char pointer - a memory address.

Are the two pointers the same? No. They are pointing at different memory addresses, so they are not the same.

If you meant to use the actual string "one" as your map key, then use strings. Not char-pointers.
Yes I meant to use "one" as a key.


My problem is that when I use map<string, int> then iterating over it will not happen in order I inserted items. When I used char*, it iterated in order I added items in this map.
When I used char*, it iterated in order I added items in this map.


Completely by chance, probably because the memory containing the strings happens to be in the same order as you are adding pointers to the map. You have no guarantee of that.

If you need a specific iteration order, you're going to have to arrange that yourself. The std::map is not the right container to use for that.

A std::map is not designed to provide that. They're in order of http://www.cplusplus.com/reference/map/map/key_comp/ , not in order of adding to the map. The map is designed to provide fast look-up ; it is not designed to provide a particular iterator order.
Last edited on
Topic archived. No new replies allowed.