Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading << operator for c++ stl containers

Tags:

c++

stl

ofstream

I wish I could just print contents of a set/vector/map by using cout << . It doesn't seem so difficult for the stl designers to implement : Assuming that << is defined for T, << for a container could just iterate through the elements and print them using ofstream << .

Is there an easy way to print them that I dont know of?

If not, Is there an easy solution? I have read at places that extending stl classes is a bad idea. Is that so, and why?

how about defining an something like an overloaded print function? EDIT: I am looking for a recursive function which can handle containers of containers of ... I agree that different people would like different formats, but something overridable is better than nothing

like image 402
Abhishek Anand Avatar asked Sep 12 '25 05:09

Abhishek Anand


2 Answers

Probably the easiest way to output an STL container is

std::copy(cont.begin(), cont.end(),
          std::ostream_iterator<Type>(std::cout, " "));

where Type is the type of the elements of cont (e.g. if cont is of type std::vector<int> then Type must be int).

Of course instead of std::cout you can use any ostream.

like image 120
celtschk Avatar answered Sep 14 '25 19:09

celtschk


The easiest eay to dump a container is probably just using std::copy(). For example I typically use something like this:

template <typename C>
std::string format(C const& c) {
    std::ostringstream out;
    out << "[";
    if (!c.empty()) {
        std::copy(c.begin(), --c.end(),
            std::ostream_iterator<typename C::value_type>(out, ", "));
            out << c.back();
    }
    out << "]";
    return out.str();
}

Yes, this doesn't always work but works for my needs. This actually shows one of the problems why there is no output for containers in the standard library: there are many different ways how containers can be formatted. To make matters worse, the formatted output should be readable where thing become real fun. All of this is doable but I'm not aware of a corresponding proposal.

like image 43
Dietmar Kühl Avatar answered Sep 14 '25 21:09

Dietmar Kühl