Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

stdvector

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

like image 983
dharag Avatar asked Mar 15 '13 14:03

dharag


1 Answers

#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;
}
like image 173
Matteo Italia Avatar answered Oct 04 '22 06:10

Matteo Italia