C++ map的一些用法

map的一些用法#

C++map的遍历##

一般使用迭代器遍历比较方便。
其中map的键是唯一的。

map<string,int> m;

map<string,int>::iterator it;

it = m.begin();

while(it != m.end())
{
    //it->first;
    //it->second;
    it ++;         
}

find函数的使用

find是用于根据键进行查找,返回值,注意是查找键。

#include<string>
#include<cstring>
#include<iostream>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
int main(){
    map<string,int> test;
    test.insert(make_pair("test1",1));//test["test1"]=1
    test.insert(make_pair("test2",2));//test["test2"]=2
    map<string,int>::iterator it;
    it=test.find("test0");
    cout<<"test0 find:";
    if(it==test.end()){
        cout<<"test0 not found"<<endl;
    }
    else{
        cout<<it->second<<endl;
    }
    cout<<"test0 count:";
    cout<<test.count("test1")<<endl;

    cout<<"test1 find:";
    it=test.find("test1");
    if(it==test.end()){
        cout<<"test1 not found"<<endl;
    }
    else{
        cout<<it->second<<endl;
    }
    cout<<"test1 count:";
    cout<<test.count("test1")<<endl;

    cout<<"after inserting test1"<<endl;
    test.insert(make_pair("test1",2));
    cout<<"test1 find:";
    it=test.find("test1");
    if(it==test.end()){
        cout<<"test1 not found"<<endl;
    }
    else{
        cout<<it->second<<endl;
    }
    cout<<"test1 count:";
    cout<<test.count("test1")<<endl;
    return 0;
}

添加元素


//验证数组形式插入数据的效果  
  
#include <map>  
  
#include <string>  
  
#include <iostream>  
  
using namespace std;  
  
int main()  
  
{  
  
    map<int, string> mapStudent;  
  
    mapStudent[1] = "student_one";  
  
    mapStudent[1] = "student_two";  
  
    mapStudent[2] = "student_three";  
  
    map<int, string>::iterator iter;  
  
    for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
  
       cout<<iter->first<<' '<<iter->second<<endl;  
}  

猜你喜欢

转载自blog.csdn.net/pan_xi_yi/article/details/85134544