Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add valid key without specifying value to a std::map?

Tags:

c++

map

I have a std::map, and I would like to add a valid key to iterate over it later, but without giving any value (it will be given later on in the course of the iterations).

This is how I do it for now :

std::vector<std::string> valid_keys;
//Fill... Then :
std::map<std::string, float> map;
for(size_t i = 0 ; i < valid_keys.size() ; ++i) {
    /*I don't want to do that because in fact I don't use a float type*/ 
    map[valid_keys[i]] = 0.f; //<- 
}
//Using :
for(std::map<std::string, float>::iterator it = map.begin() ; it != map.end() ; ++it) {
    it->second = 0; //Dummy
}

How can I do that, please ?

Thanks aforehand.

like image 908
Mister Mystère Avatar asked Aug 26 '10 16:08

Mister Mystère


People also ask

How do I add a key to just a map?

The standard solution to insert new elements into a map is using the std::map::insert function. It inserts the specified key-value pair into the map only if the key already doesn't exist. If the key already exists in the map, the element is not inserted.

Can we modify key in map?

Set of keys in Map is read-only, and you can't do changes to keys like mapRecord. keySet(). add(something) . So you can create new Map with new keys and same values.

What happens if key doesn't exist in map?

When you index a map in Go you get two return values; the second one (which is optional) is a boolean that indicates if the key exists. If the key doesn't exist, the first value will be the default zero value.

What is the complexity of std::map :: insert () method?

Time complexity: k*log(n) where n is size of map, k is no. of elements inserted.


1 Answers

I'm not entirely sure what you mean by "without giving any value" but if you mean without explicitly assigning a value then just do

map[valid_keys[i]];

This still works i.e. it creates a new entry in the map if there was not previously one with that key. The operator[] just returns a refernce to the value so that you can assign a new value to it but remember it's already been default constructed.

If, on the other hand, you mean you want to express that there is no meaningful value and it may or may not subsequently receive a valid value then see @UncleBens` answer.

like image 136
Troubadour Avatar answered Sep 17 '22 01:09

Troubadour