zoukankan      html  css  js  c++  java
  • map

    map 的遍历 

    代码示例

    #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;  // 迭代器 
        for(iter = mapStudent.begin(); iter != mapStudent.end(); iter++){
          printf("%d %d ", iter->first, iter->second); // 直接引用两个元素
        }       
    }  

    判断一个元素是否出现过

    1 . count

    mp.count( x );
    

    当 x 出现过,函数的返回值为 1 , 当没有出现过,函数的返回值为 0 。

    2 . find ();

        map<int, int>mp;
        
        mp[10] = 3; mp[20] = 5; mp[30] = 7;
        
        map<int, int>::iterator it;
        
        it = mp.find(22);
        printf("%d 
    ", it->second);
    

     若要查找的元素,则返回所要查找的元素对应的在容器中的位置,若不存在,则返回 test.end( ) 。

    删除元素 

    map<int, int>::iterator it;
    
    mp.erase( it ); //删除后 it 所指向的地址是删除元素的当前地址 。若是在遍历时删除了元素,则在遍历时在给it++,则会出现错误  好坑啊这里 !!
    

    lower_bound(  x )  函数返回大于等于 x 的第一个迭代器的位置

    int main() {
        map<int, int>mp;
        
        mp[10] = 3; mp[20] = 5; mp[30] = 7;
        
        map<int, int>::iterator it;
        it = mp.lower_bound(20); 
        printf("%d 
    ", it->second);
    
        return 0;
    }
    

    upper_bound(  x )  函数返回大于 x 的第一个迭代器的位置

    int main() {
        map<int, int>mp;
        
        mp[10] = 3; mp[20] = 5; mp[30] = 7;
        
        map<int, int>::iterator it;
        it = mp.upper_bound(20); 
        printf("%d 
    ", it->second);
    
        return 0;
    }
    
    东北日出西边雨 道是无情却有情
  • 相关阅读:
    洛谷P3768 简单的数学题 【莫比乌斯反演 + 杜教筛】
    13.1.2 拷贝赋值运算符、析构函数、三/五法则、阻止拷贝
    拷贝构造函数和深拷贝例子
    拷贝构造函数和深拷贝例子
    动态数组、allocator 类
    智能指针和异常、 weak_ptr、unique_ptr
    12.动态内存和智能指针、 直接管理内存、shared_ptr和new结合使用
    8.2 文件输入输出
    7.3 类的其他特性 笔记
    8.1.1 IO
  • 原文地址:https://www.cnblogs.com/ccut-ry/p/8058989.html
Copyright © 2011-2022 走看看