Created
November 16, 2010 13:00
-
-
Save peteb/701802 to your computer and use it in GitHub Desktop.
An iterator that casts the input data to another type. Note: std::transform should probably be used in most cases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <iostream> | |
| #include <map> | |
| #include <sstream> | |
| #include <string> | |
| #include <iterator> | |
| template <class T, class C, class charT=char, class traits=std::char_traits<charT> > | |
| class ostream_cast_iterator : | |
| public std::iterator<std::output_iterator_tag, void, void, void, void> | |
| { | |
| std::basic_ostream<charT,traits>* out_stream; | |
| const charT* delim; | |
| public: | |
| typedef charT char_type; | |
| typedef traits traits_type; | |
| typedef std::basic_ostream<charT,traits> ostream_type; | |
| ostream_cast_iterator(ostream_type& s) : out_stream(&s), delim(0) {} | |
| ostream_cast_iterator(ostream_type& s, const charT* delimiter) | |
| : out_stream(&s), delim(delimiter) { } | |
| ostream_cast_iterator(const ostream_cast_iterator<T,C,charT,traits>& x) | |
| : out_stream(x.out_stream), delim(x.delim) {} | |
| ~ostream_cast_iterator() {} | |
| ostream_cast_iterator<T,C,charT,traits>& operator= (const T& value) { | |
| *out_stream << C(value); | |
| if (delim!=0) *out_stream << delim; | |
| return *this; | |
| } | |
| ostream_cast_iterator<T,C,charT,traits>& operator*() { return *this; } | |
| ostream_cast_iterator<T,C,charT,traits>& operator++() { return *this; } | |
| ostream_cast_iterator<T,C,charT,traits>& operator++(int) { return *this; } | |
| }; | |
| class PairToString { | |
| public: | |
| template<typename T> | |
| PairToString(const T & thePair) { | |
| std::stringstream ss; | |
| ss << thePair.first << ": " << thePair.second; | |
| convertedPair = ss.str(); | |
| } | |
| operator std::string() const { | |
| return convertedPair; | |
| } | |
| private: | |
| std::string convertedPair; | |
| }; | |
| int main() { | |
| std::map<std::string, int> persons; | |
| persons["Peter"] = 34; | |
| persons["Katten"] = 88; | |
| persons["Hatten"] = 2353; | |
| persons["Reagan"] = 1337; | |
| std::copy(persons.begin(), persons.end(), ostream_cast_iterator<PairToString, std::string>(std::cout, "\n")); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment