C++ Is it possible to cout a whole vector? [duplicate]

跟風遠走 提交于 2021-02-04 16:24:05

问题


I need to cout a vector. Not just an element of it, but the whole thing. For example std::cout << vectorName; Something like that, hope it makes sense. Any ideas? Thanks in advance


回答1:


You can either define a utility function like

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

Or iterate yourself

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



回答2:


Yes, it is possible - if you define operator<< for your vector. Something like this:

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


来源:https://stackoverflow.com/questions/32785418/c-is-it-possible-to-cout-a-whole-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!