浅谈c++中的stl中的map用法详解

2020-01-06 15:47:29王冬梅

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


#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

    Map<int, string> mapStudent;

    mapStudent.insert(pair<int, string>(1, “student_one”));

    mapStudent.insert(pair<int, string>(2, “student_two”));

    mapStudent.insert(pair<int, string>(3, “student_three”));

    map<int, string>::iterator iter;

    iter = mapStudent.find(1);

if(iter != mapStudent.end())

{

    Cout<<”Find, the value is ”<<iter->second<<endl;

}

Else

{

    Cout<<”Do not Find”<<endl;

}

}

第三种:这个方法用来判定数据是否出现,是显得笨了点,但是,我打算在这里讲解

Lower_bound函数用法,这个函数用来返回要查找关键字的下界(是一个迭代器)

Upper_bound函数用法,这个函数用来返回要查找关键字的上界(是一个迭代器)

例如:map中已经插入了1,2,3,4的话,如果lower_bound(2)的话,返回的2,而upper-bound(2)的话,返回的就是3

Equal_range函数返回一个pair,pair里面第一个变量是Lower_bound返回的迭代器,pair里面第二个迭代器是Upper_bound返回的迭代器,如果这两个迭代器相等的话,则说明map中不出现这个关键字,程序说明


#include <map>

#include <string>

#include <iostream>

Using namespace std;

Int main()

{

    Map<int, string> mapStudent;

    mapStudent[1] = “student_one”;

    mapStudent[3] = “student_three”;

    mapStudent[5] = “student_five”;

    map<int, string>::iterator iter;

iter = mapStudent.lower_bound(2);

{

    //返回的是下界3的迭代器

    Cout<<iter->second<<endl;

}

iter = mapStudent.lower_bound(3);

{

    //返回的是下界3的迭代器

    Cout<<iter->second<<endl;

}

 

iter = mapStudent.upper_bound(2);

{

    //返回的是上界3的迭代器

    Cout<<iter->second<<endl;

}

iter = mapStudent.upper_bound(3);

{

    //返回的是上界5的迭代器

    Cout<<iter->second<<endl;

}

 

Pair<map<int, string>::iterator, map<int, string>::iterator> mapPair;

mapPair = mapStudent.equal_range(2);

if(mapPair.first == mapPair.second)
    {

    cout<<”Do not Find”<<endl;

}

Else

{

Cout<<”Find”<<endl;
}

mapPair = mapStudent.equal_range(3);

if(mapPair.first == mapPair.second)
    {

    cout<<”Do not Find”<<endl;

}

Else

{

Cout<<”Find”<<endl;
}

}