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;
}
  • StumbleUpon
  • Facebook
  • Digg
  • Google Buzz
  • Delicious
  • Reddit
  • MySpace
  • Share/Bookmark

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