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

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.


I suppose something that could help you out 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 available default constructor is not an issue, by default optional will be empty.


/* I don't want to do that because in fact I don't use a float type */

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

Tags:

C++

Map