std::map default value

后端 未结 12 2086
旧巷少年郎
旧巷少年郎 2020-11-28 06:09

Is there a way to specify the default value std::map\'s operator[] returns when an key does not exist?

12条回答
  •  天命终不由人
    2020-11-28 07:00

    Use std::map::insert().

    Realizing that I'm quite late to this party, but if you're interested in the behaviour of operator[] with custom defaults (that is, find the element with the given key, if it isn't present insert an element in the map with a chosen default value and return a reference to either the newly inserted value or the existing value), There is already a function available to you pre C++17: std::map::insert(). insert will not actually insert if the key already exists, but instead return an iterator to the existing value.

    Say, you wanted a map of string-to-int and inserts a default value of 42 if the key wasn't present yet:

    std::map answers;
    
    int count_answers( const std::string &question)
    {
        auto  &value = answers.insert( {question, 42}).first->second;
        return value++;
    }
    
    int main() {
    
        std::cout << count_answers( "Life, the universe and everything") << '\n';
        std::cout << count_answers( "Life, the universe and everything") << '\n';
        std::cout << count_answers( "Life, the universe and everything") << '\n';
        return 0;
    }
    

    which should output 42, 43 and 44.

    If the cost of constructing the map value is high (if either copying/moving the key or the value type is expensive), this comes at a significant performance penalty, which I think would be circumvented with C++17's try_emplace.

提交回复
热议问题