为容器定义的类型

STL为所有容器定义了下列类型:
   容器::value_type,如 vector<int>::value_type表示int类型
   (注:对于普通的就是其类型,对于map,则是pair<int, string>类型)
    容器:: reference,如list<int>::reference表示 int &
    容器:: const_reference ,如set<int>::const_reference表示const int &
    容器:: iterator ,如list<int>::iterator表示指向int的迭代器
    容器:: const_iterator ,const迭代器
    容器:: different_type ,表示2个迭代器间的距离,类似指针差值。
    容器:: size_type ,无符号整数,表示容器对象的元素个数。
STL专门为关联式容器定义的类型有:
   容器:: key_type ,表示关键字的类型,如map<int,string>::key_type=int
    容器:: mapped_type , map/multimap中值的类型,上例中的string
    容器:: key_compare , 关键字比较函数对象类, 默认为 less<Tkey>
    容器:: value_compare , 对set/multiset, 同key_compare; 对map/multimap, 为value_type提供了排序功能
#include<iostream>
#include<map>
using namespace std;
template<class container>
void print_container(container& v)
{
        for(auto& elem:v)
                cout<<elem.first<<","<<elem.second<<endl;
}
int main()
{
        //STL为所有容器定义了类型
        //这里的value_type就相当于pair<int,string>
        map<int,string>::value_type arr[4] =
        {
                map<int,string>::value_type(1,"kunming"),
                map<int,string>::value_type(3,"nanning"),
                map<int,string>::value_type(2,"guiyang"),
                map<int,string>::value_type(3,"haikou")
        };
        map<int,string> map1(arr,arr+4);
        print_container(map1);
        map<int,string>::size_type size = map1.size();
        cout<<"map1.size="<<size<<endl;
        map<int,string>::key_type cnt = map1.erase(3);
        cout<<"map1 after erase key 3"<<endl;
        print_container(map1);
        cout<<"erase count="<<cnt<<endl;
        cout<<"----华丽的分割线----"<<endl;
        multimap<int,string> mmap1(arr,arr+4);
        print_container(mmap1);
        multimap<int,string>::size_type msize = mmap1.size();
        cout<<"mmap1.size="<<msize<<endl;
        multimap<int,string>::key_type mcnt = mmap1.erase(3);
        cout<<"mmap1 after erase key 3"<<endl;
        print_container(mmap1);
        cout<<"erase count="<<mcnt<<endl;
        return 0;
}


猜你喜欢

转载自www.cnblogs.com/meihao1203/p/9006382.html