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;
    }
    
    东北日出西边雨 道是无情却有情
  • 相关阅读:
    [译]微服务-Martin Fowler(转)
    SpringBoot注解最全详解(整合超详细版本)(转)
    操作系统中的句柄是什么?(转)
    用户态和核心态(转)
    进程、线程、协程(转)
    IO中同步与异步,阻塞与非阻塞区别(转)
    HTML5常见的取值与单位
    C++实现词法分析器
    用C语言编写一个简单的词法分析程序
    Java面向对象详解
  • 原文地址:https://www.cnblogs.com/ccut-ry/p/8058989.html
Copyright © 2011-2022 走看看