c++dictionarystdmap

Trying to create a Map in C++


I am trying to create a map of stringstreams in C++

std::map<int, std::stringstream> myMap;
std::stringstream ss;
myMap.insert(std::pair<int, std::stringstream>(1, ss));

This fails to compile with

'<function-style-cast>': cannot convert from 'initializer list' to 'std::pair<int,std::stringstream>'

What does this mean and how can I resolve it?


Solution

  • The problem is that your code will require to copy the std::stringstream into the std::map, but std::stringstream is non-copyable.

    In this case you can use emplace() instead of insert() to construct the element (including the std::stringstream) in place inside the container:

    myMap.emplace(1, std::stringstream{});
    

    Live demo 1

    Alternatively (as @康桓瑋 commented), you can stay with insert(), but move (instead of copy) the std::stringstream into the container:

    std::stringstream ss;
    //------------------------------------------------vvvvvvvvv-------
    myMap.insert(std::pair<int, std::stringstream>(1, std::move(ss)));
    

    Live demo 2