5

Possible Duplicate:
C++ Vector to CSV by adding Comma after each element

I have a vector:

std::vector<std::pair<int, QString> > recordingArray;

I need to convert it to a comma delimitated string so I can store it in a database (is there a better format for the data - it all needs to go in one field)

How can I convert it to a comma delimitated string?

And then later, convert it back?

Community
  • 1
  • 1
panthro
  • 22,779
  • 66
  • 183
  • 324
  • 1
    I would take a look at boost::algorithm::join and boost::algorithm::split – frankc Dec 10 '12 at 21:18
  • 1
    Your vector is slightly the same.. the concept is the same either way. It's a duplicate. –  Dec 10 '12 at 21:18
  • You *could* use the standard library algorithms but I'd prefer to bash it out in a loop. Comma delimiting is as good as any -- provided you remember to escape literal commas, of course. – Elliott Dec 10 '12 at 21:20
  • 3
    Yeah, why would anyone think about reusing code that works and has been tested when they can reinvent all the bugs on their own. – R. Martinho Fernandes Dec 10 '12 at 21:46
  • @R.MartinhoFernandes I would suggest that if you can introduce bugs into a simple concatenation loop then programming might not be for you. – Elliott Jan 17 '17 at 03:00
  • Link to answer using boost: https://stackoverflow.com/questions/1833447/a-good-example-for-boostalgorithmjoin – frabcus May 29 '18 at 09:34

2 Answers2

17

Use std::transform and a std::stringstream for this.

std::stringstream str;

std::transform(
    recordingArray.begin(),
    recordingArray.end(),
    std::ostream_iterator<std::string>(str, ", "),
    [](const std::pair<int, QString> &p) { return std::to_string(p.first) + ", " + p.second.toStdString(); });
moswald
  • 11,491
  • 7
  • 52
  • 78
2
string line = "";
auto it = recordingArray.begin();

while(it != recordingArray.end())
{
  line.append(*it);
  line.append(',');
}

This assumes that each item is directly convertible to a string. You may need to write a toString function.

string toString(std::pair<int, QString>> input)
{
  /* convert the data to a string format */
}

Then call line.append(toString(*it)).

lcs
  • 4,227
  • 17
  • 36