Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: vector to stringstream

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?

like image 626
Alerty Avatar asked Jun 09 '10 17:06

Alerty


People also ask

Can we use StringStream in C?

StringStream in C++ is similar to cin and cout streams and allows us to work with strings. Like other streams, we can perform read, write, and clear operations on a StringStream object. The standard methods used to perform these operations are defined in the StringStream class.

How do you return a vector string in C++?

vector<string> *v = fn(&store); respectively. Note the presence and position of * in the return type of the function definition. Note the presence and position of & in the function call statement; it is in front of the argument, store, and not in front of fn(), which does not have & or *.

How do you find the size of a vector in C++?

CPP. size() – Returns the number of elements in the vector. max_size() – Returns the maximum number of elements that the vector can hold. capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements.


2 Answers

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;
like image 67
Jacob Avatar answered Oct 01 '22 19:10

Jacob


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));
like image 30
Éric Malenfant Avatar answered Oct 01 '22 19:10

Éric Malenfant