[C++]vector对<<重载

template 
std::ostream& operator << (std::ostream& out, std::vector vec) {
    out << "[";
    for (typename std::vector::iterator ite(vec.begin()); ite != vec.end(); ite++) {
        out << *ite;
        if (vec.end() != ite + 1)
            out << ", ";
    }
    out << "]";
    return out;
}

用法

std::vector v = {1,2,3};
std::cout << v << std::endl;
std::vector> vec = {{1,2,3},{4,5,6}};
std::cout << vec << std::endl;

打印map

#include 
#include 
#include 
#include 

using namespace std;

template
ostream& operator <<(ostream& os, const map &m) {
    for_each(m.begin(), m.end(), [&os](pair p) {os << "map[" << p.first << "]=" << p.second << endl; });
    return os;
}

int main() {
    map m;
    m[0] = 1;
    m[1] = 2;
    cout << m << endl;
}

你可能感兴趣的:([C++]vector对<<重载)