Avoiding key construction for std::map::find()

后端 未结 4 554
野趣味
野趣味 2020-12-29 23:46

Suppose I\'ve got a std::map. std::string can be compared to C strings (const char*) without std::string tempo

4条回答
  •  鱼传尺愫
    2020-12-29 23:57

    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;
    

提交回复
热议问题