漂亮的印刷嵌套向量 [英] pretty printing nested vectors

查看:67
本文介绍了漂亮的印刷嵌套向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码来漂亮地打印通用矢量-:

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
}  

我正在将GCC 4.9.2与<$ c一起使用$ c> -std = c ++ 14 标志。

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>')  



推荐答案

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

您正在使用复制到ostream迭代器,该迭代器未为 std的向量定义:: vector<> 。一种变通方法是根据儿童的操作员<< 实施操作员<<

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

此处为实时示例

由于 std :: vector< my_type> 如果未为类my_type

这篇关于漂亮的印刷嵌套向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆