patterncppMinor
`std::vector` 'substring concatenator'
Viewed 0 times
stdsubstringvectorconcatenator
Problem
The point of this is to concatenate a vector of
Is there anything wrong with this approach? Should I be using a stringstream or just concatenating strings?
std::strings into one string starting at an index of the vector.std::string vectorSubstr(std::vector vec, int startPos, char seperator)
{
std::stringstream ss;
for (int i = startPos; i < vec.size(); i++)
{
if (i == startPos)
{
ss << vec[i];
}
else
{
ss << seperator << vec[i];
}
}
return ss.str();
}Is there anything wrong with this approach? Should I be using a stringstream or just concatenating strings?
Solution
If you are just trying to concatenate
Simple and effective, assuming you use C++11.
If you want to change the index where you start, you could always declare an iterator as such
vector elements, why not use the following approach:std::string seperator = " ";
std::string vectorElementHolder;
for (const auto& word : vec){
vectorElementHolder += word + seperator;
}Simple and effective, assuming you use C++11.
If you want to change the index where you start, you could always declare an iterator as such
vector::iterator to point to the index and go from there.Code Snippets
std::string seperator = " ";
std::string vectorElementHolder;
for (const auto& word : vec){
vectorElementHolder += word + seperator;
}Context
StackExchange Code Review Q#92111, answer score: 2
Revisions (0)
No revisions yet.