在 C++ 中漂亮地打印 std::vector [英] Pretty-print a std::vector in C++

查看:26
本文介绍了在 C++ 中漂亮地打印 std::vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何漂亮地打印 std::vector?例如,如果我构造了一个 std::vector(6, 1),我可以运行它来获得像 {1 1 1 1 1 1}{1 1 1 1 1 1}在 C++ 中?它需要是通用的,因为大小和值可能会改变,所以 std::vector(4, 0) 将是 {0 0 0 0}.

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

推荐答案

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

然后你可以用普通的 operator<<< 语法输出你的向量:

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

std::cout<<yourVector;

您可以在此处看到这一点.

但要获得更灵活的解决方案,请查看上面链接的问题.

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

如果您不想要两个空格(开头和结尾):

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

这篇关于在 C++ 中漂亮地打印 std::vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆