Search code examples
c++vectorcompiler-errorspretty-print

pretty printing nested vectors


I have the following code to pretty-print generic vectors -:

// print a vector
template<typename T1>
std::ostream& operator <<( std::ostream& out, const std::vector<T1>& object )
{
    out << "[";
    if ( !object.empty() )
    {
        std::copy( object.begin(), --object.end(), std::ostream_iterator<T1>( out, ", " ) );
        out << *--object.end(); // print the last element separately to avoid the extra characters following it.
    }
    out << "]";
    return out;
}  

I am getting a compiler error if I try to print a nested vector from it.

int main()
{
    vector<vector<int> > a;
    vector<int> b;
    // cout << b ; // Works fine for this
    cout << a; // Compiler error
}  

I am using GCC 4.9.2 with the -std=c++14 flag.

The error message given by the compiler is -:

no match for 'operator<<' (operand types are
'std::ostream_iterator<std::vector<int>, char, std::char_traits<char>::ostream_type {aka std::basic_ostream<char>}' and 'const std::vector<int>')  

Solution

  • std::copy( object.begin(), --object.end(), std::ostream_iterator<T1>( out, ", " ) );
    

    You are using copy to ostream iterator which is not defined for vector of std::vector<>. One work around is to implement operator << in terms of operator << of children.

    if ( !object.empty() )
    {
        //std::copy( object.begin(), --object.end(), std::ostream_iterator<T1>( out, ", " ) );
        for(typename std::vector<T1>::const_iterator t = object.begin(); t != object.end() - 1; ++t) {
            out << *t << ", ";
        }
        out << *--object.end(); // print the last element separately to avoid the extra characters following it.
    }
    

    Live example here

    This method will not work for the same reason for std::vector<my_type> if opeartor << is not defined for class my_type