views:

631

answers:

5

Hello, after some years in Java and C# now I'm back to C++. Of course my programming style is influenced by those languages and I tend to feel the need of a special component that I used massively: the HASH MAP. In STL there is the hash_map, that GCC says it's deprecated and I should use unordered_map. So I turned to it. I confess I'm not sure of the portability of what I am doing as I had to use a compiler switch to turn on the feature -std=c++0x that is of the upcoming standard. Anyway I'm happy with this. As long as I can't get it working since if I put in my class

std::unordered_map<unsigned int, baseController*> actionControllers;

and in a method:

void baseController::attachActionController(unsigned int *actionArr, int len,
     baseController *controller) {
    for (int i = 0; i < len; i++){
     actionControllers.insert(actionArr[i], controller);
    }
}

it comes out with the usual ieroglyphs saying it can't find the insert around... hints?

A: 

STL insert is usually map.insert(PAIR(key, value));. Maybe that is your problem?

PAIR would be std::unordered_map<unsigned int, baseController*>::value_type

laura
whoa dude, std::make_pair is your friend.
caspin
They're the same thing, so it just boils down to preference. Some people prefer `std::make_pair`, others prefer `typedef`-ing so you can see what you're inserting. There is no other difference between the two (except perhaps the extra function call used for make_pair).
laura
+2  A: 

Try:

actionControllers.insert(std::make_pair(actionArr[i], controller));
Naveen
+17  A: 

insert takes a single argument, which is a key-value pair, of type std::pair<const key_type, value_type> . So you would use it like this:

actionControllers.insert(std::make_pair(actionArr[i], controller));
Mike Seymour
This is one case where it would be nice if the standard provided an overload to do just that.
caspin
+6  A: 

Just use:

actionControllers[ actionArr[i] ] = controller;

this is the operator overloading java owe you for ages :)

J-16 SDiZ
+1: good point. It's worth noting the difference between this and `insert`: if the map already has an entry for the key, then `map[key] = value;` will change the existing value, while `map.insert(make_pair(key,value))` won't (and has a return value to indicate that it failed).
Mike Seymour
Furthurmore, `map[key] = v` first creates an entry in the map whith the default value for the type of v, and only then copies the value v into the entry. For complicated types, there may be a difference in performance.
Xavier Nodet
+2  A: 

If you have already decided to use (expreimental and not yet ready) C++0x, then you can use such a syntax to insert a key value pair into an unordered_map:

  actionControllers.insert({ actionArr[i], controller });

This is supported by gcc 4.4.0

robson3.14