Re: cout formatting + copy algorithm
suresh <suresh.amritapuri@gmail.com> wrote:
I display a vector using copy algorithm like this.
copy(v.begin(),v.end(),ostream_iterator<int>(cout," ");
suppose i want to set the width or the fill character, what can i do?
Of course I can use a for loop instead of copy algorithm but my
question is, while using copy algorithm, is it possible to format
output?
You can do it, but is it worth it?
template < typename T, typename Elem = char, typename Tr =
char_traits<Elem> >
struct OStreamIteratorWidth : iterator<output_iterator_tag, void, void,
void, void> {
typedef Elem char_type;
typedef Tr traits_type;
typedef basic_ostream<Elem, Tr> ostream_type;
OStreamIteratorWidth(ostream_type& o) : os(o), wi(0) { }
OStreamIteratorWidth(ostream_type& o, int w): os(o), wi(w) { }
OStreamIteratorWidth& operator*() { return *this; }
OStreamIteratorWidth& operator++() { return *this; }
OStreamIteratorWidth operator++(int) { return *this; }
OStreamIteratorWidth& operator=(const T& t) {
os << setw(wi) << t;
return *this;
}
private:
ostream_type& os;
int wi;
};
void fn(vector<int>& v) {
copy(v.begin(), v.end(), OStreamIteratorWidth<int>(cout, 5));
}
using for_each is moderately easier:
template < typename T >
struct OutputWithWidth : unary_function<T, void>
{
ostream& os;
int width;
OutputWithWidth(ostream& o, int w): os(o), width(w) { }
void operator()(const T& t) {
os << setw(width) << t;
}
};
void fn(vector<int>& v) {
for_each(v.begin(), v.end(), OutputWithWidth<int>(cout, 5));
}
which points to a straight loop:
void fn(vector<int>& v) {
for (vector<int>::const_iterator it = v.begin(); it != v.end(); ++it)
cout << setw(5) << *it;
}