首页 > 其他 > 详细

谈谈map中的count方法

时间:2016-01-21 00:24:53      阅读:287      评论:0      收藏:0      [点我收藏+]

map和set两种容器的底层结构都是红黑树,所以容器中不会出现相同的元素,因此count()的结果只能为0和1,可以以此来判断键值元素是否存在(当然也可以使用find()方法判断键值是否存在)。

拿map<key,value>举例,find()方法返回值是一个迭代器,成功返回迭代器指向要查找的元素,失败返回的迭代器指向end。count()方法返回值是一个整数,1表示有这个元素,0表示没有这个元素。

#include<iostream>
#include<map>
#include<string>
using namespace std;

int main()
{
    map<int,string>maps;
    if(maps.find(1)==maps.end())
    {
        cout<<"没有1这个元素"<<endl;
    }
    if(maps.count(1)==0)
    {
        cout<<"没有1这个元素"<<endl;
    }
    //添加元素1
    maps[1]="one";

    if(maps.find(1)!=maps.end())
    {
        cout<<"有1这个元素"<<endl;
    }
    if(maps.count(1))
    {
        cout<<"有1这个元素"<<endl;
    }
    return 0;
}

 

谈谈map中的count方法

原文:http://www.cnblogs.com/bewolf/p/5146787.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!