C++ 31 Jan 2010 23:37:58

Snippet: Vector to Output Stream

http://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;
}
StumbleUponFacebookDiggDeliciousRedditMySpaceShare

One Response 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).

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.
Click to hear an audio file of the anti-spam word