首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++ primer中的一个例子程序,不明白multiset的count成员怎么统计容器中相同元素的个数

2012-05-10 
c++ primer中的一个例子程序,不明白multiset的count成员如何统计容器中相同元素的个数中文版第四版,511页

c++ primer中的一个例子程序,不明白multiset的count成员如何统计容器中相同元素的个数
中文版第四版,511页中间:sum += (*iter) -> net_price(items.count(*iter));

items是一个multiset,iter是指向它的迭代器,并且multiset自定义了一个比较函数来比较multiset内元素的"<"关系,但是multiset内的元素类并没有定义"=="操作符,没有定义<操作符。

十分困惑的是,count用什么来进行统计?众所周知它的作用是统计参数元素在容器中出现的次数,但是这里没有定义任何标准判断哪个元素和哪个元素相同,哪个元素和哪个元素不同。如果说它利用自定义的比较函数,那最多能知道元素之间的"<"关系,也无法区别相同元素(按照<关系定义,相同元素之间进行比较返回false,左操作数大于右操作数也返回false)

[解决办法]
呵呵,楼主要晓得在STL里面一般都是严格定义“<"就可以做比较操作的了。比如">"就是使用操作符"<"的相反来获得。而”=="也通过“<"来实现的。比如已经实现了"<",如果这样比较A>B的话就调用了B<A。如果这样比较A==B的话,调用的是(!A<B)&&(!B<A)来实现
[解决办法]
只要有小于的实现,实际上等于也可以实现的(!(a<b)) &&(!(a>b))
[解决办法]
看代码就更明白了。

C/C++ code
_Paircc _Eqrange(const key_type& _Keyval) const        {    // find leftmost node not less than _Keyval        _Nodeptr _Pnode = _Root();        _Nodeptr _Lonode = _Myhead;    // end() if search fails        _Nodeptr _Hinode = _Myhead;    // end() if search fails        while (!_Isnil(_Pnode))            if (_DEBUG_LT_PRED(this->comp, _Key(_Pnode), _Keyval))                _Pnode = _Right(_Pnode);    // descend right subtree            else                {    // _Pnode not less than _Keyval, remember it                if (_Isnil(_Hinode)                        && _DEBUG_LT_PRED(this->comp, _Keyval, _Key(_Pnode)))                    _Hinode = _Pnode;    // _Pnode greater, remember it                _Lonode = _Pnode;                _Pnode = _Left(_Pnode);    // descend left subtree                }        _Pnode = _Isnil(_Hinode) ? _Root()            : _Left(_Hinode);    // continue scan for upper bound        while (!_Isnil(_Pnode))            if (_DEBUG_LT_PRED(this->comp, _Keyval, _Key(_Pnode)))                {    // _Pnode greater than _Keyval, remember it                _Hinode = _Pnode;                _Pnode = _Left(_Pnode);    // descend left subtree                }            else                _Pnode = _Right(_Pnode);    // descend right subtree        const_iterator _First = _TREE_CONST_ITERATOR(_Lonode);        const_iterator _Last = _TREE_CONST_ITERATOR(_Hinode);        return (_Paircc(_First, _Last));        } 

热点排行