join using template function
I used a template function to join the vector items, and removed the unnecessary if statement by iterating through only the first to penultimate items in the vector, then joining the last item after the for loop. This also obviates the need for extra code to remove the extra separator at the end of the joined string. So, no if statements slowing down the iteration and no superfluous separator that needs tidying up.
This produces an elegant function call to join a vector of string, integer, or double, etc.
I wrote two versions: one returns a string; the other writes directly to a stream.
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
// Return a string of joined vector items.
template<typename T>
string join(const vector<T>& v, const string& sep)
{
ostringstream oss;
const auto LAST = v.end() - 1;
// Iterate through the first to penultimate items appending the separator.
for (typename vector<T>::const_iterator p = v.begin(); p != LAST; ++p)
{
oss << *p << sep;
}
// Join the last item without a separator.
oss << *LAST;
return oss.str();
}
// Write joined vector items directly to a stream.
template<typename T>
void join(const vector<T>& v, const string& sep, ostream& os)
{
const auto LAST = v.end() - 1;
// Iterate through the first to penultimate items appending the separator.
for (typename vector<T>::const_iterator p = v.begin(); p != LAST; ++p)
{
os << *p << sep;
}
// Join the last item without a separator.
os << *LAST;
}
int main()
{
vector<string> strings
{
"Joined",
"from",
"beginning",
"to",
"end"
};
vector<int> integers{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
vector<double> doubles{ 1.2, 3.4, 5.6, 7.8, 9.0 };
cout << join(strings, "... ") << endl << endl;
cout << join(integers, ", ") << endl << endl;
cout << join(doubles, "; ") << endl << endl;
join(strings, "... ", cout);
cout << endl << endl;
join(integers, ", ", cout);
cout << endl << endl;
join(doubles, "; ", cout);
cout << endl << endl;
return 0;
}
Output
Joined... from... beginning... to... end
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
1.2; 3.4; 5.6; 7.8; 9
Joined... from... beginning... to... end
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
1.2; 3.4; 5.6; 7.8; 9