std::vectorの出力

Pythonだと、

v1 = ["foo","bar","baz"]
print v1

['foo', 'bar', 'baz']

になるのに、C++で同じ事はできなくてデバッグがちょっと面倒だと思っていたけど、自分で書けば良いのか。

template <class T>ostream &operator<<(ostream &o,const vector<T>&v)
{o<<"{";for(int i=0;i<(int)v.size();i++)o<<(i>0?", ":"")<<v[i];o<<"}";return o;}

使用例。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

template <class T>ostream &operator<<(ostream &o,const vector<T>&v)
{o<<"{";for(int i=0;i<(int)v.size();i++)o<<(i>0?", ":"")<<v[i];o<<"}";return o;}

int main()
{
    vector<string> v1;
    v1.push_back("foo");
    v1.push_back("bar");
    v1.push_back("baz");
    cout << v1 << endl;

    vector<vector<int> > v2(3,vector<int>(3));
    for ( int i=0; i<3; i++ )
    for ( int j=0; j<3; j++ )
        v2[i][j] = i+j;

    cout << v2 << endl;
}

出力。多次元配列でもOK。

{foo, bar, baz}
{{0, 1, 2}, {1, 2, 3}, {2, 3, 4}}