漂亮的印刷嵌套矢量图

pretty printing nested 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;
}  

如果我尝试从中打印嵌套向量,则会出现编译器错误。

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

我正在使用带有 -std=c++14 标志的 GCC 4.9.2。

编译器给出的错误信息是-:

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>')  
std::copy( object.begin(), --object.end(), std::ostream_iterator<T1>( out, ", " ) );

您正在使用未为 std::vector<> 的向量定义的复制到 ostream 迭代器。一种解决方法是根据 children 的 operator << 实施 operator <<

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

如果未为 class my_type

定义 opeartor <<,则由于 std::vector<my_type> 的相同原因,此方法将不起作用

只需使用普通的 forloop 而不是 std::copy 即可解决此问题。正如@Mohit 所建议的,没有为嵌套向量定义 ostream 迭代器。

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>
using namespace std;

// print a vector
template<typename T1>
std::ostream& operator <<( std::ostream& out, const std::vector<T1>& object )
{
    out << "[";
    if ( !object.empty() )
    {
        for(typename std::vector<T1>::const_iterator
            iter = object.begin();
            iter != --object.end();
            ++iter) {
                out << *iter << ", ";
        }
        out << *--object.end();
    }
    out << "]";
    return out;
}

int main() {
    std::vector<std::vector<int> > a;
    std::vector<int> b;
    b.push_back(1);
    b.push_back(2);
    std::vector<int> c;
    c.push_back(3);
    c.push_back(4);
    std::cout << b << std::endl;
    std::cout << c << std::endl;
    a.push_back(b);
    a.push_back(c);
    cout << a; // Compiler error
    return 0;
}

输出将如下所示:

[1, 2]
[3, 4]
[[1, 2], [3, 4]]