2015-06-30 66 views
3

我有下面的代碼漂亮地打印通用矢量 - :漂亮的印刷嵌套向量

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

我正在使用GCC 4.9.2和-std=c++14標誌。

由編譯器給定的錯誤信息是: -

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
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 <<工作不是爲class my_type

2

定義只使用一個正常的for循環,而不是的std ::副本將解決這個問題。正如@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]]