其他分享
首页 > 其他分享> > c – 为什么map :: operator []设计缓慢?

c – 为什么map :: operator []设计缓慢?

作者:互联网

问题:

Peope抱怨这个:
In STL maps, is it better to use map::insert than []?

访问时

std::map<Key, ExpensiveDefaultConstructorValue> data;
data[key1] // <-- Calls default constructor each time it is called, 
           // even when the element is there

实现简单而优雅,但效率很低(从unordered_map中获取).

_Tp& operator[](const key_type& __key)
   { return _M_ht.find_or_insert(value_type(__key, _Tp())).second; }

明显的解决方案

_Tp& operator[](const key_type& __key)
   { return _M_ht.find_or_insert_default(key_type(__key)).second; }

find_or_insert_default只在需要时调用_Tp()(即元素不存在)

为什么不?

是否有一些其他问题可能是由于这种悲观的方法在建立一个新元素之前知道你需要它?

这是标准库,他们应该竭尽全力优化它.为什么不使用这种简单的方法?

解决方法:

至少自g++ 4.5以来,std :: map一直没有这样的问题:

// stripped comments and requirements
mapped_type&
operator[](const key_type& __k)
{    
    iterator __i = lower_bound(__k);

    if (__i == end() || key_comp()(__k, (*__i).first))
        __i = insert(__i, value_type(__k, mapped_type()));
    return (*__i).second;
}

您发布的代码段不是来自std :: map,而是来自hash_map,它是该库的GCC extension

00052 /** @file backward/hash_map
00053  *  This file is a GNU extension to the Standard C++ Library (possibly
00054  *  containing extensions from the HP/SGI STL subset).
00055  */

由于它是一个扩展,维护者没有义务遵循任何复杂性/性能规则(即使你提出的功能会更快).请注意,hash_map已被std :: unordered_map的实现替换,如果元素存在,则不使用构造函数.

标签:c,performance,stl,std,libstdc
来源: https://codeday.me/bug/20190831/1775429.html