Sunday, April 28, 2019

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



I have the following:



#include 
#include
#include

int main() {

std::vector> 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}};



Answer



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



std::vector> data = {{{"close", 14.4}}, {{"close", 15.6}}};
^ ^ ^ ^



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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...