漂亮的打印嵌套向量

时间:2015-06-30 05:29:26

标签: c++ vector compiler-errors pretty-print

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

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

2 个答案:

答案 0 :(得分:2)

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

您正在使用复制到ostream迭代器,该迭代器未针对std::vector<>的向量定义。一个解决方法是在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

如果std::vector<my_type>未定义opeartor << <{1}},则此方法的效果与class my_type相同

答案 1 :(得分:2)

使用普通的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]]