2015-09-25 64 views
0

我需要關閉一個向量。不僅僅是它的一個元素,而是整個事物。 例如std :: cout < < vectorName; 這樣的事情,希望它是有道理的。 有什麼建議嗎? 在此先感謝C++是否可以關閉整個向量?

+2

'std :: copy'是你的朋友。 –

+0

似乎相關:http://stackoverflow.com/q/4850473/2069064 – Barry

+0

@UlrichEckhardt上帝沒有。 – Barry

回答

3

您可以定義一個效用函數像

template <typename T> 
ostream& operator<<(ostream& output, std::vector<T> const& values) 
{ 
    for (auto const& value : values) 
    { 
     output << value << std::endl; 
    } 
    return output; 
} 

或者重複自己

for (auto const& value : values) 
{ 
    std::cout << value << std::endl; 
} 
1

是的,這是可能的 - 如果你定義operator < <您的載體。類似這樣的:

template <class T> 
std::ostream& operator<<(ostream& out, const std::vector<T>& container) { 
    out << "Container dump begins: "; 
    std::copy(container.cbegin(), container.cend(), std::ostream_iterator<T>(" ", out)); 
    out << "\n"; 
    return out; 
} 
相關問題