BabyishTank
BabyishTank

Reputation: 1482

Using ostream_iterator to copy a map into file

I have a STL map of type<string, int> , I need to copy that map into a file, but I am having trouble putting the type of ostream_iterator

map<string, int> M;

ofstream out("file.txt");
copy( begin(M), end(M), ostream_iterator<string, int>(out , "\n") );  

Error message error: no matching function for call to 'std::ostream_iterator, int>::ostream_iterator(std::ofstream&, const char [2])'|

since map M is a type , why doesn't ostream_iterator take its type?

Upvotes: 2

Views: 2823

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

If you look carefully at the declaration of std::ostream_iterator here, you will notice that your usage of std::ostream_iterator is incorrect because you should specify the type of printed elements as the first template parameter.

The type of elements in the std::map M is std::pair< const std::string, int >. But you can't put std::pair< const std::string, int > as the first template parameter because there is no default way to print an std::pair.

One possible workaround is to use std::for_each and lambda:

std::ofstream out("file.txt");

std::for_each(std::begin(M), std::end(M),
    [&out](const std::pair<const std::string, int>& element) {
        out << element.first << " " << element.second << std::endl;
    }
);

Upvotes: 8

Related Questions