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

后端 未结 5 1171
不知归路
不知归路 2021-02-20 05:10

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).

5条回答
  •  死守一世寂寞
    2021-02-20 05:27

    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.

提交回复
热议问题