检查std :: map中是否存在 - count vs find

dol*_*phy 43 c++ stl stdmap map

因此,似乎有两种通常可接受的方法来确定密钥是否存在于std :: map中:

map.find(key) != map.end()
map.count(key) > 0
Run Code Online (Sandbox Code Playgroud)

一个比另一个更有效吗?具体来说,count()的概念可以被解释为意味着该方法将迭代每个键,计算总计数(并且由于std :: map的定义,总计数将始终为0或1).count()保证在匹配后"停止",以与find()相同的复杂度运行吗?

Ker*_* SB 44

由于地图最多只能有一个键,count因此在找到一个元素后基本上会停止.但是,鉴于更常见的容器(如multimaps和multisets),find如果只关心是否存在具有此键的某个元素,则严格要好,因为一旦找到第一个匹配元素,它就能真正停止.

一般来说,无论countfind作者会使用特定容器的查找方法(树遍历或哈希表查找),它总是相当有效.只是count必须继续迭代直到等范围的结束,而find不是.此外,您的代码应记录意图,因此如果您想要查找内容,请使用find.

  • @dolphy:正如我试图说的那样,该地图使用其内部数据结构进行查找,因此对于给定的键,它将有效地查找具有该键的所有元素的范围(例如,在树中进行二进制搜索),并为`count `它将返回该范围的长度。 (2认同)

小智 11

根据源代码,我建议使用find.查看源代码.

在GCC中,代码如下(stl_map.h):

    const_iterator
    find(const key_type& __x) const
    { return _M_t.find(__x); }

    size_type                                                                              
    count(const key_type& __x) const                                                       
    { return _M_t.find(__x) == _M_t.end() ? 0 : 1; }  
Run Code Online (Sandbox Code Playgroud)

在Windows平台上的Visual Studio中,代码如下(xtree):

    const_iterator find(const key_type& _Keyval) const
    {   // find an element in nonmutable sequence that matches _Keyval
        const_iterator _Where = lower_bound(_Keyval);
        return (_Where == end()
            || _DEBUG_LT_PRED(this->_Getcomp(),
                _Keyval, this->_Key(_Where._Mynode()))
                    ? end() : _Where);
    }

    //....

    const_iterator lower_bound(const key_type& _Keyval) const
    {   // find leftmost node not less than _Keyval in nonmutable tree
        return (const_iterator(_Lbound(_Keyval), this));
    }

    //....

    _Nodeptr _Lbound(const key_type& _Keyval) const
    {   // find leftmost node not less than _Keyval
        _Nodeptr _Pnode = _Root();
        _Nodeptr _Wherenode = this->_Myhead;    // end() if search fails

        while (!this->_Isnil(_Pnode))
            if (_DEBUG_LT_PRED(this->_Getcomp(), this->_Key(_Pnode), _Keyval))
                _Pnode = this->_Right(_Pnode);  // descend right subtree
            else
                {   // _Pnode not less than _Keyval, remember it
                _Wherenode = _Pnode;
                _Pnode = this->_Left(_Pnode);   // descend left subtree
                }

        return (_Wherenode);    // return best remembered candidate
    }

    //..........................................
    //..........................................

    size_type count(const key_type& _Keyval) const
    {   // count all elements that match _Keyval
        _Paircc _Ans = equal_range(_Keyval);
        size_type _Num = 0;
        _Distance(_Ans.first, _Ans.second, _Num);
        return (_Num);
    }

    //....

    _Pairii equal_range(const key_type& _Keyval) const
    {   // find range equivalent to _Keyval in nonmutable tree
        return (_Eqrange(_Keyval));
    }

    //....

    _Paircc _Eqrange(const key_type& _Keyval) const
    {   // find leftmost node not less than _Keyval
        _Nodeptr _Pnode = _Root();
        _Nodeptr _Lonode = this->_Myhead;   // end() if search fails
        _Nodeptr _Hinode = this->_Myhead;   // end() if search fails

        while (!this->_Isnil(_Pnode))
            if (_DEBUG_LT_PRED(this->_Getcomp(), this->_Key(_Pnode), _Keyval))
                _Pnode = this->_Right(_Pnode);  // descend right subtree
            else
                {   // _Pnode not less than _Keyval, remember it
                if (this->_Isnil(_Hinode)
                        && _DEBUG_LT_PRED(this->_Getcomp(), _Keyval,
                        this->_Key(_Pnode)))
                    _Hinode = _Pnode;   // _Pnode greater, remember it
                _Lonode = _Pnode;
                _Pnode = this->_Left(_Pnode);   // descend left subtree
                }

        _Pnode = this->_Isnil(_Hinode) ? _Root()
            : this->_Left(_Hinode); // continue scan for upper bound
        while (!this->_Isnil(_Pnode))
            if (_DEBUG_LT_PRED(this->_Getcomp(), _Keyval, this->_Key(_Pnode)))
                {   // _Pnode greater than _Keyval, remember it
                _Hinode = _Pnode;
                _Pnode = this->_Left(_Pnode);   // descend left subtree
                }
            else
                _Pnode = this->_Right(_Pnode);  // descend right subtree

        const_iterator _First = const_iterator(_Lonode, this);
        const_iterator _Last = const_iterator(_Hinode, this);
        return (_Paircc(_First, _Last));
    }
Run Code Online (Sandbox Code Playgroud)

  • 使用 find 的参数是什么?GCC 示例表明 count 是通过 find 实现的,那么为什么在这种情况下我应该更喜欢 find 呢? (2认同)

Sag*_*Jha 7

如果您只想查找键是否存在,而不关心值,最好使用map::count它,因为它只返回一个整数。map::find返回一个迭代器,因此通过使用count,您将节省迭代器的构造。

  • 正如您在源代码(另一个答案)中看到的那样-与“find”的实现相比,“count”的实现在内部构造了更多的迭代器。 (11认同)