Pretty-print a std::vector in C++ [duplicate]

旧城冷巷雨未停 提交于 2019-12-10 18:34:16

问题


How can I pretty-print a std::vector? For example, if I construct a std::vector<int>(6, 1), what can I run it through to get output like {1 1 1 1 1 1} in C++? It needs to be generic as the size and value might change, so std::vector<int>(4, 0) would be {0 0 0 0}.


回答1:


#include <vector>
#include <algorithm>
#include <iterator>

template<typename T>
std::ostream & operator<<(std::ostream & os, std::vector<T> vec)
{
    os<<"{ ";
    std::copy(vec.begin(), vec.end(), std::ostream_iterator<T>(os, " "));
    os<<"}";
    return os;
}

then you can output your vectors with the normal operator<< syntax:

std::cout<<yourVector;

you can see this in action here.

But for more flexible solutions have a look at the question linked above.


Edit: if you don't want the two spaces (at the beginning and at the end):

template<typename T>
std::ostream & operator<<(std::ostream & os, std::vector<T> vec)
{
    os<<"{";
    if(vec.size()!=0)
    {
        std::copy(vec.begin(), vec.end()-1, std::ostream_iterator<T>(os, " "));
        os<<vec.back();
    }
    os<<"}";
    return os;
}


来源:https://stackoverflow.com/questions/15435313/pretty-print-a-stdvector-in-c

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