jeudi 1 juin 2017

Constructing strings for appending

I have to construct a string by concatenating a few other strings. I also know the maximum size of the string, and I want to reserve the capacity so there are no reallocations. My code right now looks something like this:

#include <string>
using std::string;

// Setup
...

string a,b,c;

// Strings are filled with relevant data
...

string msg;
msg.reserve(200);
msg = "A=";  msg += a; msg += ',';
msg += "B="; msg += b; msg += ',';
msg += "C="; msg += c; msg += '.';

I previously used stringstream for this, but performance was twice as slow. Is there a way to reserve the string capacity at construction, instead of having to allocate memory twice? Also is there a better (faster) way of appending the strings?

Aucun commentaire:

Enregistrer un commentaire