C++: vector to stringstream

26,983

Solution 1

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;

Solution 2

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));
Share:
26,983
Alerty
Author by

Alerty

This is me!

Updated on July 05, 2022

Comments

  • Alerty
    Alerty almost 2 years

    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?

  • Skurmedel
    Skurmedel almost 14 years
    +1 only crux is that copy and ostream_iterator should be qualified with std. :)
  • Robben_Ford_Fan_boy
    Robben_Ford_Fan_boy almost 14 years
    Would you not give the benefit of the doubt that using namespace std was at the start of the method?!!! :)
  • Harsh Pathak
    Harsh Pathak almost 14 years
    Lol, might as well be consistent :)
  • Edward Strange
    Edward Strange almost 14 years
    No no no! It must transform the vector!
  • Harsh Pathak
    Harsh Pathak almost 14 years
    @Noah: Lol, do you propose a change of basis or a magic potion :) ?
  • Dai Doan
    Dai Doan almost 14 years
    This fails when the vector's element type has no operator<<. I think the OP needs to specify the problem more.
  • Skurmedel
    Skurmedel almost 14 years
    @David Relihan: I'm sure there were, but it could be confusing. :)