I want to know if it is possible to transform a std::vector to a std::stringstream using generic programming and how can one accomplish such a thing?
+13
A:
Adapting Brian Neal's comment, the following will only work if the <<
operator is defined for the object in the std::vector
(in this example, std::string
).
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <iterator>
// Dummy std::vector of strings
std::vector<std::string> sentence;
sentence.push_back("aa");
sentence.push_back("ab");
// Required std::stringstream object
std::stringstream ss;
// Populate
std::copy(sentence.begin(), sentence.end(),std::ostream_iterator<std::string>(ss,"\n"));
// Display
std::cout<<ss.str()<<std::endl;
Jacob
2010-06-09 17:13:11
+1 Yep, that's the cleanest way
David Relihan
2010-06-09 17:15:21
+1 only crux is that copy and ostream_iterator should be qualified with std. :)
Skurmedel
2010-06-09 17:15:38
@Skurmedel - Just saw it, thanks :)
Jacob
2010-06-09 17:16:55
Would you not give the benefit of the doubt that using namespace std was at the start of the method?!!! :)
David Relihan
2010-06-09 17:19:01
Lol, might as well be consistent :)
Jacob
2010-06-09 17:19:38
No no no! It must *transform* the vector!
Noah Roberts
2010-06-09 17:26:08
@Noah: Lol, do you propose a change of basis or a magic potion :) ?
Jacob
2010-06-09 17:27:35
This fails when the vector's element type has no `operator<<`. I think the OP needs to specify the problem more.
Brian Neal
2010-06-09 19:26:37
@David Relihan: I'm sure there were, but it could be confusing. :)
Skurmedel
2010-06-09 20:34:09
+8
A:
If the vector's element type supports operator<<, something like the following may be an option:
std::vector<Foo> v = ...;
std::ostringstream s;
std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(s));
Éric Malenfant
2010-06-09 17:13:58