Convert vector<int> to delimited string

Viewed 6062

As I see here there is a fast and short way to Convert vector to string separated with a character in c#:

var result = string.Join(";", data); 
var result = string.Join(";", data.Select(x => x.ToString()).ToArray()); 

I wan to know is there a same way in c++ to do this?

2 Answers

Expanding on the accepted answer a little, I took the code and made a generic template version that works not only with a vector of ints but works with any types that work with stringstream:

template <typename T>
std::string VectorToCSV(const std::vector<T>& vec)
{
    std::ostringstream out;
    if (!vec.empty())
    {
        std::copy(std::begin(vec), std::end(vec) - 1, std::ostream_iterator<T>(out, ";"));
        out << vec.back();
    }

    return out.str();
}

This works with Template Argument Deduction, so to call it like this:

// Vector of ints example
std::vector<int> vec_of_ints = { 1, 2, 3, 4};    
std::string ints_csv = VectorToCSV(vec_of_ints);

// Vector of strings example
std::vector<std::string> vec_of_strings = { "Hello", "World"};
std::string strings_csv = VectorToCSV(vec_of_strings);
Related