A
Andrea Crotti
I wanted something to display my vectors easily and in a nice way.
From the following site the "shortest" solution was this:
// from http://bytes.com/topic/c/answers/133231-print-elements-vector discussion
template <typename T>
void displayContainer(const T& v) {
copy(v.begin(), v.end(), ostream_iterator<typename T::value_type>(cout, ", "));
}
But I don't like it so much actually.
Also because if I want to add it to a class which uses a buffer, I would
like to do
ostream& operator<<(ostream& s, const MyClass& c)
{
s << c.vec;
return s;
}
which in this case is not possible but I have instead to call a
function.
I thought that something like this would be possible
template <typename T>
ostream& operator<<(ostream& s, const vector<T>& vec)
{
typename vector<T>::iterator iter;
for (iter=vec.begin(); iter!=vec.end(); ++iter) {
s << (*iter);
}
return s;
}
But actually I guess it's not, since then I don't know how to pass the
template parameter and I get this erro
try.cpp: In function ‘std:stream& operator<<(std:stream&, const std::vector<T, std::allocator<_CharT> >&) [with T = int]’:
try.cpp:21: instantiated from here
try.cpp:12: error: no match for ‘operator=’ in ‘iter = ((const
std::vector<int, std::allocator<int> >*)vec)->std::vector<_Tp,
_Alloc>::begin [with _Tp = int, _Alloc = std::allocator<int>]()’
From the following site the "shortest" solution was this:
// from http://bytes.com/topic/c/answers/133231-print-elements-vector discussion
template <typename T>
void displayContainer(const T& v) {
copy(v.begin(), v.end(), ostream_iterator<typename T::value_type>(cout, ", "));
}
But I don't like it so much actually.
Also because if I want to add it to a class which uses a buffer, I would
like to do
ostream& operator<<(ostream& s, const MyClass& c)
{
s << c.vec;
return s;
}
which in this case is not possible but I have instead to call a
function.
I thought that something like this would be possible
template <typename T>
ostream& operator<<(ostream& s, const vector<T>& vec)
{
typename vector<T>::iterator iter;
for (iter=vec.begin(); iter!=vec.end(); ++iter) {
s << (*iter);
}
return s;
}
But actually I guess it's not, since then I don't know how to pass the
template parameter and I get this erro
try.cpp: In function ‘std:stream& operator<<(std:stream&, const std::vector<T, std::allocator<_CharT> >&) [with T = int]’:
try.cpp:21: instantiated from here
try.cpp:12: error: no match for ‘operator=’ in ‘iter = ((const
std::vector<int, std::allocator<int> >*)vec)->std::vector<_Tp,
_Alloc>::begin [with _Tp = int, _Alloc = std::allocator<int>]()’