overloading << operator for c++ stl containe

2020-04-17 05:22发布

问题:

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

回答1:

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.



回答2:

In C++11 you can use range-based for:

for (auto& i: container)  cout << i << "  ";
cout << endl;


回答3:

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.



回答4:

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 << .

Of course it is not hard for them. However, ask yourself: Does the format of the output make sense for every client? The standard library is about reuse and genericity. Coupling containers with some arbitrary output formatting rules makes them less generic for the sake of only some.

The recommended solution therefore is to provide your own operator<<(std::ostream &, T) and/or to take other generic algorithms, as found in e.g. <algorithms>.



标签: c++ stl ofstream