简体   繁体   English

将键添加到std :: map中,但不带值

[英]Add a key to std::map without a value

Suppose i defined a global map - 假设我定义了一个全局地图-

map<int,list<char>> cMap;

Is there a way ( without using the boost library ) that i can add integer keys, and later on in the program add values to the lists that correspond to them? 有没有一种方法( 不使用boost )我可以添加整数键,然后在程序中稍后将值添加到与它们相对应的列表中?

map<int,list<char>> cmap;

int main()
{

// Add only a value this way?
cmap[2];

// and then -
cmap[2].push_back('A');
return 0;
}

You're already doing it. 您已经在做了。

When you write cmap[2] , and that element doesn't exist, it is created and default-constructed. 当您编写cmap[2] ,该元素不存在,它将被创建并默认构造。

So, cmap[2] will be an empty list. 因此, cmap[2]将是一个空列表。 Then you can .push_back to it whenever you like. 然后,您可以.push_back将其.push_back返回。

Since this process is also triggered by the cmap[2] in cmap[2].push_back(..) , you don't actually need the initial "empty" initialisation unless there's some requirement in your project for the key to exist in the map from the start (in which case, fair enough). 由于这一过程也被触发cmap[2]cmap[2].push_back(..)你实际上并不需要最初的“空”的初始化,除非有一个在你的项目中的某些需求为重点,以中存在从一开始就绘制地图(在这种情况下,足够公平)。

If you don't want an empty list to be the value but for there to be no value, I think that this is silly but you have some options: 如果您不希望空列表成为值,而又不希望有任何值,那么我认为这很愚蠢,但是您可以选择以下方法:

  • Don't add the key, either 也不要添加密钥
    (let the lack of the key mean lack of the value) ; (让缺少键意味着缺少值)
  • Store std::unique_ptr<std::list<char>> and start off with nullptr 存储std::unique_ptr<std::list<char>>并从nullptr开始
    (yuk; dynamic allocation for no good reason; no thanks!) ; (yuk;没有充分的理由就进行动态分配;不,谢谢!)
  • Store std::optional<std::list<char>> and start off with cmap[2] = std::none 存储std::optional<std::list<char>>并从cmap[2] = std::none
    (when Boost.Optional makes it into C++, which is happening but slowly) . (当Boost.Optional进入C ++时,这种情况正在发生,但进展缓慢)

And… that's it. 而且...就是这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM