C ++ vector for semicolon separator string?

Possible duplicate:
C ++ Vector for CSV by adding a comma after each element

I have a vector:

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

I need to convert it to a comma delimited string so that I can store it in the database (is there a better format for the data - all this needs to be done in one field)

How to convert it to comma delimited string?

And then, convert it back?

+4
source share
2 answers

Use std::transform and 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(); }); 
+16
source
 string line = ""; auto it = recordingArray.begin(); while(it != recordingArray.end()) { line.append(*it); line.append(','); } 

This assumes that each element is directly converted 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)) .

+2
source

All Articles