Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert vector<int> to delimited string

Tags:

c++

string

vector

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?

like image 626
thirdDeveloper Avatar asked Dec 28 '13 17:12

thirdDeveloper


People also ask

How do I turn a vector into a string?

Convert Vector to String using toString() function To convert elements of a Vector to Strings in R, use the toString() function. The toString() is an inbuilt R function used to produce a single character string describing an R object.

How do you return a vector string in C++?

Returning a Vector Pointervector<string> *v = fn(&store); respectively. Note the presence and position of * in the return type of the function definition. Note the presence and position of & in the function call statement; it is in front of the argument, store, and not in front of fn(), which does not have & or *.


1 Answers

#include <sstream>
#include <string>
#include <vector>
#include <iterator>
#include <iostream>

int main()
{
    std::vector<int> data = {42, 1, 2, 3, 4, 5};

    std::ostringstream oss;
    std::copy(data.begin(), data.end(), std::ostream_iterator<int>(oss, ";"));

    std::string result( oss.str() );
    std::cout << result << "\n";
}

N.B. In C++11, you can use the more general form

using std::begin;
using std::end;
std::copy(begin(data), end(data), std::ostream_iterator<int>(oss, ";"));

Where the using-declarations are not required if ADL can be used (like in the example above).


Also possible, but maybe a bit less efficient:

std::string s;
for(auto const& e : v) s += std::to_string(e) + ";";

which can be written via std::accumulate in <algorithm> as:

std::string s = std::accumulate(begin(v), end(v), std::string{},
    [](std::string r, int p){ return std::move(r) + std::to_string(p) + ";"; });

(IIRC there was some method to eliminate the copying, maybe by taking the lambda-parameter by reference std::string& r.)


A version w/o the trailing semi-colon (thanks to Dietmar Kühl):

std::vector<int> data = {42, 1, 2, 3, 4, 5};

std::ostringstream out;
if (!v.empty())
{
    std::copy(v.begin(), v.end() - 1, std::ostream_iterator<int>(out, ";"));
    out << v.back();
}

std::string result( out.str() );
std::cout << result << "\n";
like image 113
dyp Avatar answered Oct 05 '22 12:10

dyp