如何添加有效的密钥而不指定一个std :: map的值? [英] How to add valid key without specifying value to a std::map?

查看:118
本文介绍了如何添加有效的密钥而不指定一个std :: map的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个std :: map,我想添加一个有效的密钥来迭代它,但是没有给出任何值(稍后会在迭代中给出)。



这是我现在所做的:

  std: :矢量<的std :: string> valid_keys; 
// Fill ... Then:
std :: map< std :: string,float>地图;
(size_t i = 0; i< valid_keys.size(); ++ i){
/ *我不想这样做,因为实际上我不使用浮点型* /
map [valid_keys [i]] = 0.f; //< -
}
//使用:
for(std :: map< std :: string,float> :: iterator it = map.begin(); it!= map.end(); ++ it){
it-> second = 0; // Dummy
}

请问怎么做?



感谢前面。

解决方案

我不完全确定你的意思是没有给出任何值,但如果您的意思是没有明确指定值,那么只需执行

  map [valid_keys [i]]; 

这仍然工作,即它在地图中创建一个新条目,如果之前没有该键。 operator [] 只是返回一个参考值,以便您可以为其分配一个新值,但请记住它已被默认构造。 / p>

另一方面,如果您的意思是要表示没有有意义的价值,它可能或可能不会随后收到有效的值,那么请参阅 @ UncleBens答案


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.

解决方案

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.

这篇关于如何添加有效的密钥而不指定一个std :: map的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆