zoukankan      html  css  js  c++  java
  • Map和Set简单使用

    学过红黑树之后,就自然学到了map和set,作为STL中较为普遍用到的容器,我们应该熟练的使用它,下面简单介绍他们的具体使用

    map 和set的底层就是红黑树,map是K,V模型,而set是K模型。

    map的简单介绍

    这里写图片描述
    以上就是map的内部实现的成员函数,构造,插入删除,等。map作为K,V模型,可以有很多用途,比如实现一个字典。

    map实现一个字典

    #include<iostream>
    using namespace std;
    #include <map>
    #include<string>
    int main()
    {
        map<string,string> dict;
        dict.insert(make_pair("left","左边"));
        dict.insert(make_pair("right","右边"));
        dict.insert(make_pair("left","剩余"));
        dict.insert(make_pair("hello","你好"));
        map<string,string>::iterator it = dict.begin();
        while(it!=dict.end())
        {
            cout<<it->first<<":"<<it->second<<endl;
            ++it;
        }
    

    运行结果如下图
    这里写图片描述
    我们可以看到第二个left的意思并没有加进去,这是因为底层红黑树的原因,当 插入相同的元素,就不插入。所以map也可以用来去重。
    1. map中的insert如下:
    <1> pair

    string strs[] = {"hello","tmp","hello","sort","tmp","tmp","tmp",
            "left","sort","hello","hello","hello"};
        map<string,int> countmap;
        for(size_t i = 0;i<sizeof(strs)/sizeof(strs[0]);++i)
        {
            countmap[strs[i]]++;
        }

    利用了 insert的返回值 pair结构体中的第二个参数。

    set的简单使用

    insert 和map类似:
    <1>pair

    void settest()
    {
        set<int> s;
        int arr[] = {3,6,7,9,1,9,5,4};
        for(size_t i=0;i<sizeof(arr)/sizeof(arr[0]);++i)
        {
            s.insert(arr[i]);
        }
        set<int>::iterator it = s.begin();
        while(it!=s.end())
        {
            cout<<*it<<" ";
            ++it;
        }
        cout<<endl;
    }

    注意:set没有operator[ ]
    其他的接口和map都是基本一样的,map有的它都有
    还有一个接口,介绍一下,就是count()
    size_type count (const value_type& val) const;
    他可以用来判断有没有这样一个元素

    cout<<s.count(10)<<endl;//不存在 输出0
    cout<<s.count(5)<<endl;//存在  输出1
  • 相关阅读:
    数组和字符串长度length
    Eclipse最有用快捷键整理
    Eclipse编辑java文件报Unhandled event loop exception错误的解决办法
    Java 删除项目中的.svn信息
    oracle 删除外键约束 禁用约束 启用约束
    Java Sftp上传下载文件
    java 如何判断操作系统是Linux还是Windows
    Javascript-正则表达式-开发中的使用.
    Eclipse和PyDev搭建完美Python开发环境 Windows篇
    ExtJS4为form表单必填项添加红色*标识
  • 原文地址:https://www.cnblogs.com/chan0311/p/9427322.html
Copyright © 2011-2022 走看看