I know how to add integers to strings, but I’m not sure I’m doing it in an efficient matters. I have a class where I often have to return a string plus an integer (a different integer each time), in Java I would do something like
public class MyClass {
final static String S = "MYSTRING";
private int id = 0;
public String getString() {
return S + (id++);
}
}
But in C++ I have to do;
class MyClass {
private:
std::string S; // For some reason I can't do const std::string S = "MYSTRING";
int id;
public:
MyClass() {
S = "MYSTRING";
id = 0;
}
std::string getString() {
std::ostringstream oss;
oss << S << id++;
return oss.str();
}
}
An additional constraint: I don’t want (in fact, in can’t) use Boost or any other librairies, I’ll have to work with the standard library.
So the thing is; the code works, but in C++ I have to create a bunch of ostringstream objects, so it seems inefficient. To be fair, perhaps Java do the same and I just don’t notice it, I say it’s inefficient mostly because I know very little about strings.
Is there a more efficient way to do this ?
std::ostringstreamis the “standard” way to do this in C++. You might be able to make something more efficient via some custom coding, or laboriously comparing the performance ofostringstream,itoa, andsprintfon all the systems where you’ll be deploying this program, but it’s probably not worth the effort.I’d say the real problem with the
std::ostringstreamsolution is not about efficiency. The real problem is that the code just looks too complicated.I know you don’t want to use Boost, but if you look at Herb Sutter’s The String Formatters of Manor Farm, you could just copy the (very tiny) definition of the
lexical_cast<>()template into your program. Then your code would look like this:Whether this is more efficient than your existing solution depends on a lot of factors (how well your compiler inlines template instantiations, for example), but it definitely looks cleaner.