Re: something like Perl's join function
Irek Szczesniak wrote:
I like the Perl's join function and want to get something similar in
C++, preferably with std or boost. In Perl you can say:
print join(", ", (10, 2, 15));
which prints "10, 2, 15".
In C++ you can get a similar thing this way:
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
int main()
{
int table[] = {10, 2, 15};
copy(table, table + 3, ostream_iterator<int>(cout, ", "));
}
However, you get "10, 2, 15, ", i.e. you get a trailing unwanted ", ".
Do you know some nifty way of getting the functionality of the Perl's
join function?
A quick implementation of mine:
#include <ostream>
#include <iterator>
template <typename T, typename CharT = char,
typename Traits = std::char_traits<CharT> >
class ostream_join_iterator
: public std::iterator<std::output_iterator_tag, void, void, void, void>
{
public:
typedef CharT char_type;
typedef Traits traits_type;
typedef std::basic_ostream<CharT, Traits> ostream_type;
ostream_join_iterator(ostream_type& s, const char_type* c = 0)
: stream(&s), string(c), print_string(0) { }
ostream_join_iterator& operator=(const T& value)
{
if (print_string) *stream << print_string;
print_string = string;
*stream << value;
return *this;
}
ostream_join_iterator& operator*() { return *this; }
ostream_join_iterator& operator++() { return *this; }
ostream_join_iterator& operator++(int) { return *this; }
private:
ostream_type* stream;
const char_type* string;
const char_type* print_string;
};
Use this as a replacement of std::ostream_iterator:
std::copy(begin, end, ostream_join_iterator<int>(std::cout, ", "));
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]