C++ 31 Jan 2010 23:37:58
Snippet: Vector to Output Stream
//tinodidriksen.com/uploads/code/cpp/vector-to-ostream.cpp
#include <ostream>
#include <iostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& stm, const std::vector<T>& obj) {
    stm << "[";
    if (!obj.empty()) {
        for (size_t i = 0 ; i<obj.size()-1 ; ++i) {
            stm << obj[i] << ",";
        }
        stm << obj.back();
    }
    stm << "]";
    return stm;
}
int main() {
    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(2);
    vec.push_back(5);
    vec.push_back(6);
    vec.push_back(1);
    std::cout << vec << std::endl;
}
				

on 19 Mar 2012 at 11:59:41 1.Pierre said …
copy(vec.begin(), vec.end(), ostream_iterator(std::cout,”,”);
Work as good as you ask. (You have to add the “[” and “]” manually).
on 19 Nov 2014 at 21:24:02 2.Petr said …
Pierre, no it doesn’t. It adds one more copy of delimiter after all the elements are processed.