Suppose I\'ve got a std::map
. std::string
can be compared to C strings (const char*) without std::string
tempo
If the construction of a string from a literal is really a measured performance bottleneck for you, you can use your own class instead of a std::string
that holds either a string or a pointer to a literal. The downside is some extra complication, plus adding the size of a pointer to the elements you're inserting into the container. Note that the value is immutable as required by map
, so it's safe to store the results of c_str
.
class mystring
{
std::string str;
const char * value;
public:
mystring() : value(NULL)
{
}
void setString(const std::string & s)
{
assert(value == NULL);
str = s;
value = str.c_str();
}
void setLiteral(const char * s)
{
assert(value == NULL);
value = s;
}
bool operator<(const mystring & rhs)
{
return strcmp(literal, rhs.literal) < 0;
}
};
std::map m;
mystring text;
text.setString(some_key);
m.insert(std::make_pair(text, some_data));
// ...
mystring key;
key.setLiteral("Olaf");
m[key] = new_value;