Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize an std::vector of std::map items?

I have the following:

#include <vector>
#include <map>
#include <string>

int main() {
    std::vector<std::map<std::string, double>> data = {{"close", 14.4}, {"close", 15.6}};

    return 0;
}

And when I try to compile, I get the following error:

g++ -std=c++11 -Wall -pedantic ./test.cpp

./test.cpp:6:49: error: no matching constructor for initialization of 'std::vector >' (aka 'vector, allocator >, double> >') std::vector> data = {{"close", 14.4}, {"close", 15.6}};

like image 948
Chad Johnson Avatar asked Oct 15 '25 14:10

Chad Johnson


1 Answers

You need an extra pair of braces for each element/pair:

std::vector<std::map<std::string, double>> data = {{{"close", 14.4}}, {{"close", 15.6}}};
                                                    ^             ^    ^             ^

The extra pair of braces is needed because std::map elements are of type std::pair<const key_type, value_type> in your case std::pair<const std::string, double>. Thus, you need an extra pair of braces to signify to the compiler the initialization of the std::pair elements.

like image 113
101010 Avatar answered Oct 18 '25 06:10

101010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!