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

I have std :: map, and I would like to add the correct key to repeat it later, but without a value (it will be specified later during iterations).

Here's how I do it 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 this, please?

Thanks in advance.

+7
c ++ map
source share
4 answers

I'm not quite sure what you mean by β€œwithout any value,” but if you mean without explicitly assigning a value, just do

 map[valid_keys[i]]; 

This still works, that is, it creates a new record on the map if there was no key with this key before. operator[] just returns a reference to the value so you can assign it a new value, but remember that it has already been configured by default.

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

+10
source share

I suggest something that might help you is Boost.Optional .

 #include <boost/optional.hpp> #include <map> class CantConstructMe { CantConstructMe() {} }; int main() { std::map<int, boost::optional<CantConstructMe> > m; m[0]; } 

The lack of an accessible default constructor is not a problem; by default, optional will be empty.

+7
source share

/ * I do not want to do this, because in fact I do not use the float type * /

Then, instead of std::map use std::set .

+5
source share

It seems that you really need a std :: set or std :: key list, and then go through this set later to create your map.

If for some reason this is unacceptable, you can wrap your float with some type of object that implements the float () operator and various conversion functions for float, but also has the flag "good ()" or somesuch.

If your final values ​​are actually floating, you can initialize the values ​​to +/- NaN as a simple placeholder.

I would say that boost :: optional is the best option for production code, but it depends on your requirements.

0
source share

All Articles