Chad Johnson
Chad Johnson

Reputation: 21895

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}};

Upvotes: 4

Views: 2946

Answers (2)

maxadorable
maxadorable

Reputation: 1284

Use 3 braces instead of 2.

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

Its what chad said.

Upvotes: 5

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42899

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.

Upvotes: 6

Related Questions