19

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?

Evg
  • 25,259
  • 5
  • 41
  • 83
Alerty
  • 5,945
  • 7
  • 38
  • 62

2 Answers2

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
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