| re: vectorstream analogous to std::stringstream
"Marcin Kalicinski" <kalita@poczta.onet.pl> wrote in message
news:0gRFf.37855$Rw6.15581@newsfe7-gui.ntli.net...
| Is there a vectorstream class that implements the functionality
similar to
| std::stringstream but with std::vector, not std::string?
|
| cheers,
| Marcin
|
No, since a std::string is a predefined entity while a vector could be a
vector of anything.
However, encapsulating a templated vector and overloading a global
operator<< and operator>> to stream a vector's contents is a trivial
exercise with great benefits.
_____
// Container.h
#include <vector>
#include <algorithm>
#include <iterator>
template< class T >
class Container
{
std::vector< T > vt;
public:
Container() : vt() { }
Container(const Container& copy_)
{
vt = copy_.vt; // or std::swap
}
~Container() { }
/* member functions */
void push_back(T t)
{
vt.push_back(t);
}
/* friends */
friend std::ostream& operator<<(std::ostream&, const Container&);
}; // class Container
template< class T >
std::ostream& operator<<(std::ostream& os, const Container< T >& cont)
{
std::copy( cont.vt.begin(),
cont.vt.end(),
std::ostream_iterator< T >(os, " ") );
return os;
}
__________
// test.cpp
#include <iostream>
#include <ostream>
#include "Container.h"
int main()
{
Container<int> container;
for (int i = 0; i < 10; ++i)
{
container.push_back(i);
}
std::cout << container << std::endl;
Container<int> c2(container); // copy
std::cout << c2 << std::endl;
return 0;
}
/*
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
*/
And that Container can be a container of anything, including a container
of a complex user-type with itself having an appropriate operator<<
overload.
To give you a perspective of the power and flexibility involved, lets
have the container display its size and then its contents. Thats a
simple modification.
template< class T >
std::ostream& operator<<(std::ostream& os, const Container< T >& cont)
{
os << "container size = " << cont.vt.size() << "\n"; // mod
std::copy( cont.vt.begin(),
cont.vt.end(),
std::ostream_iterator< T >(os, " ") );
return os;
}
/*
container size = 10
0 1 2 3 4 5 6 7 8 9
container size = 10
0 1 2 3 4 5 6 7 8 9
*/
Do you see why no std::vectorstream was ever included with the standard?
What if i wanted a comma between the elements? What if i wanted no
spaces?
While some languages limit you to a finite number of tools and
possibilities: standard C++ begs, pleads and becons you to create,
fashion and expand what is available with relatively little effort. |