Alex Goft
Alex Goft

Reputation: 1124

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?

map<int,list<char>> cmap;

int main()
{

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

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

Upvotes: 2

Views: 5857

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

You're already doing it.

When you write cmap[2], and that element doesn't exist, it is created and default-constructed.

So, cmap[2] will be an empty list. Then you can .push_back to it whenever you like.

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

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
    (yuk; dynamic allocation for no good reason; no thanks!);
  • Store std::optional<std::list<char>> and start off with cmap[2] = std::none
    (when Boost.Optional makes it into C++, which is happening but slowly).

And… that's it.

Upvotes: 13

Related Questions