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?
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.
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 *.
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.
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;
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With