I'm writing a utility function which will take a vector of elements (could be string, int, double, char) and concatenate into a single string and return it. It looks like this:
template<typename T>
std::string convert2Str(std::vector<T> const& vec)
{
std::ostringstream sStream;
for (size_t k=0; k<vec.size(); ++k) {
sStream << vec[k] << " ";
}
return sStream.str();
}
I would like to make this function more generic:
- First use iterators instead of using indices for the
vector<T>
. I tried thisstd::vector<T>::const_iterator it = vec.begin()
before the loop and the compiler gave me an error: : error: expected;
before it When I change the above defintions tostd::vector<std::string>::const_iterator it = vec.begin()
the error goes away. So, it looks like I'm not following correct syntax, please let me know what it is - Second is to make the function more generic by making the first argument container independent. Given any container (
vector
,list
,queue
,deque
, etc.) I want to do the same thing as above. I tried searching for this in stackoverflow and did not find satisfactory answer.