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?
Asked
Active
Viewed 3.1k times
19
-
Those seem like wholly unrelated types – Michael Mrozek Jun 09 '10 at 17:10
-
@Michael Mrozek: So I should assign the contents of the vector to the stringstream. – Alerty Jun 09 '10 at 17:13
-
Please define more what you mean by "transform". What should be inserted into the stringstream? The vector elements? Should they be delimited in some way? – Brian Neal Jun 09 '10 at 19:24
2 Answers
42
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
- 34,255
- 14
- 110
- 165
-
1+1 only crux is that copy and ostream_iterator should be qualified with std. :) – Skurmedel Jun 09 '10 at 17:15
-
1Would you not give the benefit of the doubt that using namespace std was at the start of the method?!!! :) – Robben_Ford_Fan_boy Jun 09 '10 at 17:19
-
1
-
1
-
2
-
This fails when the vector's element type has no `operator<<`. I think the OP needs to specify the problem more. – Brian Neal Jun 09 '10 at 19:26
-
16
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));

Pavel Minaev
- 99,783
- 25
- 219
- 289

Éric Malenfant
- 13,938
- 1
- 40
- 42