C++: how to initialize vector in map with non-zero size

  • A+
Category:Languages

I have a map of vectors:

std::map<int, std::vector<bool>> mymap 

At times, I need to insert a new element:

auto& newvec = mymap[42]; // Add stuff to newvec 

As far is I understand (and assuming that 42 is not yet in the map), this will give me newvec with length 0 (constructed as std::vector<bool> {}) which I can then extend.

Is there a way to initialize the vector to some size n right away?

(I am not concerned about performance, just wondering if there is a way to do this).

 


Use map::try_emplace() (or map::emplace() before C++17)

std::vector has a constructor which takes an initial size and an initial uniform value. In your case, suppose you want 125 as the initial size. With a stand-alone vector, you would use:

size_t num_bools_we_want = 1234; std::vector<bool> my_vec(num_bools_we_want, false); 

Now, std::map has a method named map::try_emplace() which forwards arguments to a constructor of the value type, which effectively allows you to choose the constructor it will use for a new element. Here's how to use it

mymap.try_emplace(42, num_bools_we_want, false); 

to create a value of std::vector<bool>(num_bools_we_want, false) for the key 42. No temporary vectors are created (regardless of compiler optimizations).

The only "problem" with this solution is that try_emplace() only exists since C++17. Since you asked about C++11 - that version of the standard introduced map::emplace(), which does almost the same thing except for an issue with making a copy of the key. See this question for a discussion of the difference between emplace() and try_emplace().

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: