c++ - 漂亮的打印嵌套 vector 图

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

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

// 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;
}  

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

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<> 的 vector 定义的复制到 ostream 迭代器.一种解决方法是实现 operator <<operator << 方面的 child 。

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 <<没有为 class my_type 定义

关于c++ - 漂亮的打印嵌套 vector 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31130243/

相关文章:

java - 查找 vector 的重复项并删除,保留平行 vector 的顺序

c++ - 是否初始化基元 - C++

c++ - 为什么带有多个 copy_n() 的 std::istream_iterator<> 总是写入第一个值

c++ - "vector subscript out of range"错误错误(VS2013)

c++ - 简单代码需要帮助——没有构造函数的实例匹配参数列表

c - Windows 上的 GCC 创建不可删除的文件

c++ - 数组作为函数参数 - 编译错误

java - System.getProperty ("java.classpath") = null?

c++ - 成员函数指针转换

c++ - ZeroMQ中定义的smessage()方法在哪个头文件中?