C++ map vs map performance (I know, “again?”)

前端 未结 6 1885
北恋
北恋 2020-12-24 11:05

I was using a map with a std::string key and while everything was working fine I wasn\'t getting the performance I expected. I searched for places to optimize

6条回答
  •  囚心锁ツ
    2020-12-24 11:43

    As sth noted, the issue is one of specifications of the associative containers (sets and maps), in that their member search methods always force a conversion to the key_type, even if an operator< exists that would accept to compare your key against the keys in the map despite their different types.

    On the other hand, the functions in do not suffer from this, for example lower_bound is defined as:

    template< class ForwardIt, class T >
    ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value );
    
    template< class ForwardIt, class T, class Compare >
    ForwardIt lower_bound( ForwardIt first, ForwardIt last, const T& value, Compare comp );
    

    So, an alternative could be:

    std::vector< std::pair< std::string, int > >
    

    And then you could do:

    std::lower_bound(vec.begin(), vec.end(), std::make_pair("hello", 0), CompareFirst{})
    

    Where CompareFirst is defined as:

    struct CompareFirst {
         template 
         bool operator()(T const& t, U const& u) const { return t.first < u.first; }
    };
    

    Or even build a completely custom comparator (but it's a bit harder).

    A vector of pair is generally more efficient in read-heavy loads, so it's really to store a configuration for example.

    I do advise to provide methods to wrap the accesses. lower_bound is pretty low-level.

提交回复
热议问题