Here is an alternative which uses a custom output iterator. This example behaves correctly for the case of an empty list. This example demonstrates how to create a custom output iterator, similar to std::ostream_iterator
.
#include <iterator>
#include <vector>
#include <iostream>
#include <sstream>
struct CommaIterator
:
public std::iterator<std::output_iterator_tag, void, void, void, void>
{
std::ostream *os;
std::string comma;
bool first;
CommaIterator(std::ostream& os, const std::string& comma)
:
os(&os), comma(comma), first(true)
{
}
CommaIterator& operator++() { return *this; }
CommaIterator& operator++(int) { return *this; }
CommaIterator& operator*() { return *this; }
template <class T>
CommaIterator& operator=(const T& t) {
if(first)
first = false;
else
*os << comma;
*os << t;
return *this;
}
};
int main () {
// The vector to convert
std::vector<int> v(3,3);
// Convert vector to string
std::ostringstream oss;
std::copy(v.begin(), v.end(), CommaIterator(oss, ","));
std::string result = oss.str();
const char *c_result = result.c_str();
// Display the result;
std::cout << c_result << "\n";
}