我有以下代码来漂亮地打印通用 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.
}
由于与 std::vector<my_type>
相同的原因,此方法将不起作用。如果opeartor <<
没有为 class my_type
定义
关于c++ - 漂亮的打印嵌套 vector 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31130243/