C++中map的查找和删除

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89816404

一 map的查找

1 点睛

这里给出2种常用的数据查找方法。

第1种:用count函数来判断关键字是否出现,其缺点是无法定位数据出现的位置,由于map的一对一的映射特性,就决定了count函数的返回值只有两个,要么是0,要么是1,当要判断关键字出现时返回1.

第2种:用find函数来定位数据出现的位置,它返回一个迭代器,当数据出现时,它返回数据所在位置的迭代器;如果map中没有要查找的数据,它返回的迭代器等于end函数返回的迭代器。

2 代码

#include<map>
#include<string>
#include<iostream>
using namespace std;
int main(){
    map<int,string> mapStudent;
    mapStudent[1] = "student_one";
    mapStudent[2] = "student_two";
    mapStudent[3] = "student_three";
     map<int, string>::iterator iter=mapStudent.find(1);
     if(iter != mapStudent.end()){
          cout<<"Found, the value is "<<iter->second<<endl;
     }else{
          cout<<"Do not found"<<endl;
    }
     return 0;
}

3 运行

[root@localhost charpter03]# g++ 0325.cpp -o 0325
[root@localhost charpter03]# ./0325
Found, the value is student_one

二 map的删除

1 点睛

函数原型:

void erase (iterator position);
size_type erase (const key_type& x);
void erase (iterator first, iterator last);

函数功能:

erase函数的作用是从map容器中移除一个元素或一些元素。

第1个函数的作用是移除迭代器position指定的元素。

第2个函数移除关键字x的元素。

第3个函数移除范围为[first,last)的元素序列。

函数参数:

参数position:迭代器,指向要删除的元素。

参数x:元素的关键字。

参数first和last:迭代器,表示要删除的元素范围是[first,last)

函数返回值:

第1个函数和第3个参数没有返回值。

第2个函数返回值是删除元素的个数。

2 代码

#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(){
    map<int, string> mapStudent;
    mapStudent[1]="student_one";
    mapStudent[2]="student_two";
    mapStudent[3]="student_three";
    mapStudent[4]="student_four";    
    map<int, string>::iterator iter=mapStudent.begin();
    for(;iter!=mapStudent.end();){
        if((*iter).second=="student_one"){
            mapStudent.erase(iter++);
        }
        else{
            ++iter;
        }
    }    
    for(iter=mapStudent.begin();iter!=mapStudent.end();iter++){
        cout<<iter->first<<" "<<iter->second<<endl;
    }
    return 0;
}

3 运行

[root@localhost charpter03]# g++ 0326.cpp -o 0326
[root@localhost charpter03]# ./0326
2 student_two
3 student_three
4 student_four

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89816404
今日推荐