Printing the contents of STL containers in a generic way

A generic Print function A way of using STL algorithms combined with template functions as a means of printing the contents of any type of STL container (eg a std::vector), containing any generic data type (eg int, std::string etc). typename T defines the generic data type held by the container, while typename InputIterator describes the STL container iterators passed to it: [code language="cpp"] template<typename T, typename InputIterator> void Print(std::ostream& ostr, InputIterator itbegin, InputIterator itend, const std::string& delimiter) { std::copy(itbegin, itend, std::ostream_iterator<T>(ostr, delimiter.c_str())); } [/code] Example 1: std::set containing std::strings This following example shows how the generic Print function can output a std::set containing std::string data types: [code language="cpp"] #include <iostream> #include <algorithm> #include <iterator> #include <string> #include set> typedef std::set<std::string>::iterator iter_s; template<typename T, typename InputIterator> void Print(std::ostream& ostr, InputIterator itbegin, InputIterator itend, const std::string& delimiter) { std::copy(itbegin, itend, std::ostream_iterator<T>(ostr, delimiter.c_str())); } int main() { std::string str[] = { "The", "cat", "in", "the", "hat" }; std::set<std::string> s( str, str + sizeof( str ) / sizeof( str[ 0 ] ) ); Print<std::string, iter_s>( std::cout, s.begin(), s.end(), "\n" ); return 0; } [/code] Giving the following tokenized string output, delimited by newline characters, though not necessarily in the order they were inserted!
The
cat
hat
in
the
Example 2: std::vector containing ints The following example shows how the same generic Print function can be used to output a std::vector containing int data types: [code language="cpp"] #include <iostream> #include <algorithm> #include <iterator> #include <string> #include <vector> typedef std::vector<int>::iterator iter; template<typename T, typename InputIterator> void Print(std::ostream& ostr, InputIterator itbegin, InputIterator itend, const std::string& delimiter) { std::copy(itbegin, itend, std::ostream_iterator<T>(ostr, delimiter.c_str())); } int main() { int vals[] = { 1, 2, 3, 4 }; std::vector<int> v( vals, vals + sizeof( vals ) / sizeof( vals[ 0 ] ) ); Print<int, iter>( std::cout, v.begin(), v.end(), " " ); return 0; } [/code] Which print the set of integers stored in the std::vector, separated by whitespaces:
1 2 3 4

Comments

Popular posts from this blog

Using the Supervisor Controller Pattern to access View controls in MVVM

Getting started with client-server applications in C++

How to send an e-mail via Google SMTP using C#