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

2 Responses to “Snippet: Vector to Output Stream”

  1. 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).

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

Subscribe to the comments through RSS Feed

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image