Practice6_map_count_find

map使用count(key)或者迭代器find(key)查找元素是否存在。

两种场景:

1.如果只是判断是否存在,使用count(key);

2.如果要获取存在的元素值,使用迭代器find(key)。

// Practice6_map.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <map>
#include <string>
#include <iostream>

using namespace std;

string strs[5] = {"huawei", "xiaomi", "meizu", "oppo", "vivo"};
/* 在构造map容器后,我们就可以往里面插入数据了。这里讲三种插入数据的方法*/
/* 第一种方法,用insert函数插入pair数据*/
void initMapByPair(map<int, string> &mapStu)
{
    mapStu.insert(pair<int, string>(12, strs[0]));
    mapStu.insert(pair<int, string>(23, strs[1]));
    mapStu.insert(pair<int, string>(38, strs[2]));
    mapStu.insert(pair<int, string>(31, strs[3]));
    mapStu.insert(pair<int, string>(31, strs[4]));
}

/* 第二种方法(与第一种等同),用insert函数插入value_type数据*/
void initMapByValue_Type(map<int, string> &mapStu)
{
    mapStu.insert(map<int, string>::value_type(12, strs[0]));
    mapStu.insert(map<int, string>::value_type(23, strs[1]));
    mapStu.insert(map<int, string>::value_type(38, strs[2]));
    mapStu.insert(map<int, string>::value_type(31, strs[3]));
    mapStu.insert(map<int, string>::value_type(31, strs[4]));
}

/* 第三种方法,用array方式填充map数据,与前面两种方法不同,这种方法遇到相同的key会覆盖掉前面的*/
void initMapByArray(map<int, string> &mapStu)
{
    mapStu[12] = strs[0];
    mapStu[23] = strs[1];
    mapStu[38] = strs[2];
    mapStu[31] = strs[3];
    mapStu[31] = strs[4];
}

void printMapStu(map<int, string> mapStu)
{
    map<int, string>::iterator it = mapStu.begin();
    for(; it != mapStu.end(); it++)
    {
        cout << it->first << "," << it->second << endl;//使用first,second取出map的key及value
    }
}

/* 用find函数来定位数据出现位置,它返回的一个迭代器位置*/
bool isExsitElement(map<int, string> mapStu, int key)
{
    map<int, string>::iterator iter = mapStu.find(key);//如果遍历到了最后,说明不存在,就返回end()
    if(iter != mapStu.end())
    {
        cout << "the key is exsit: " << iter->first << "value: " << iter->second << endl;
        return true;
    }
    cout << "the key is not exsit!" << endl; 
    return false;
}

int _tmain(int argc, _TCHAR* argv[])
{
    map<int, string> mapStudent;
    initMapByPair(mapStudent);
    //initMapByValue_Type(mapStudent);
    //initMapByArray(mapStudent);//此种方式会覆盖,但仍保持key唯一,仍会按照key排序

    printMapStu(mapStudent);

    /* 用count函数来判定关键字是否出现,其缺点是无法定位数据出现位置,只能返回0或1*/
    cout << "if the mapStudent contain(12): " << mapStudent.count(12) << endl;
    cout << "if the mapStudent contain(15): " << mapStudent.count(15) << endl;

    /* 用find函数来定位数据出现位置,它返回的一个迭代器位置*/
    isExsitElement(mapStudent, 12);
    isExsitElement(mapStudent, 15);
    return 0;
}

运行结果:

12,huawei
23,xiaomi
31,oppo
38,meizu
if the mapStudent contain(12): 1
if the mapStudent contain(15): 0
the key is exsit: 12,value: huawei
the key 15 is not exsit!

原文地址:https://www.cnblogs.com/liuzc/p/6498339.html