• c++ map


    C++ MAP

    参考链接:https://blog.csdn.net/sevenjoin/article/details/81943864

    map是STL的一个关联容器,它提供一对一的hash。map內部的实现自建一颗红黑树,如下:

    img

    应用举例:增 查 删

    // 定义一个map对象
    map<int, string> mapStudent;
    // 第一种 用insert函數插入pair
    mapStudent.insert(pair<int, string>(000, "student_zero"));
    // 第二种 用insert函数插入value_type数据
    mapStudent.insert(map<int, string>::value_type(001, "student_one"));
    // 第三种 用"array"方式插入
    mapStudent[123] = "student_first";
    mapStudent[456] = "student_second";
    
    //emplace 
    auto result = mapStudent.emplace(pair<int, string>(3, "student_three"));
    auto result_ptr = result.first; // 插入后元素指针
    bool result_bool = result.second;   //插入是否成功
    
    // find 返回迭代器指向当前查找元素的位置否则返回map::end()位置
    iter = mapStudent.find("123");
     
    if(iter != mapStudent.end())
           cout<<"Find, the value is"<<iter->second<<endl;
    else
       cout<<"Do not Find"<<endl;
    
    
    //迭代器刪除
    iter = mapStudent.find("123");
    mapStudent.erase(iter);
     
    //用关键字刪除
    int n = mapStudent.erase("123"); //如果刪除了會返回1,否則返回0
     
    //用迭代器范围刪除 : 把整个map清空
    mapStudent.erase(mapStudent.begin(), mapStudent.end());
    //等同于mapStudent.clear()
    
    

    at 访问

    map<int ,int> m;
    m[1]=111;
    m[2]=222;
    m[3]=333;
    cout<<m.at(4);
    

    first & second

    The elements of a map<string,int> are of type pair<string,int>;
    The first member of a pair is called first and the second member second.

     map<string, int> words;
     for(string s; cin >> s;)
         ++words[s];
     for(const auto& p :words)
         cout << p.first << ": " << p.second << "
    ";
    
         C++ maps是一种关联式容器,包含“关键字/值”对
         begin()         返回指向map头部的迭代器
         clear()        删除所有元素
         count()         返回指定元素出现的次数
         empty()         如果map为空则返回true
         end()           返回指向map末尾的迭代器
         equal_range()   返回特殊条目的迭代器对
         erase()         删除一个元素
         find()          查找一个元素
         get_allocator() 返回map的配置器
         insert()        插入元素
         key_comp()      返回比较元素key的函数
         lower_bound()   返回键值>=给定元素的第一个位置
         max_size()      返回可以容纳的最大元素个数
         rbegin()        返回一个指向map尾部的逆向迭代器
         rend()          返回一个指向map头部的逆向迭代器
         size()          返回map中元素的个数
         swap()           交换两个map
         upper_bound()    返回键值>给定元素的第一个位置
         value_comp()     返回比较元素value的函数
    
  • 相关阅读:
    思考题
    对敏捷开发的见解
    Code Review(自评)
    求数组最大子数组和
    [ASP.NET]在虚拟目录中禁止web.config继承IIS根目录的web.config的配置
    客户的真实需求
    利用using和try/finally語句來清理資源.
    《代码整洁之道》简单总结
    ASP.NET页面级别的事
    根据DIV移动生成图片
  • 原文地址:https://www.cnblogs.com/heimazaifei/p/12437082.html
Copyright © 2020-2023  润新知