C++STLトレーナー(mapの使用)

2700 ワード

  • vectorの使用
  • listの使用
  • dequeの使用
  • setの使用
  • mapの使用
  • multisetの使用
  • multimapの使用
  • #include   
    #include   
    #include   
    using namespace std;  
      
    int main()  
    {  
        ///1.      
        map mapStudent;  
        map::iterator iter, beg, end;  
      
        ///2.       
        mapStudent[0] = "student_one";  
        mapStudent[1] = "student_two";  
        mapStudent[2] = "student_three";  
        mapStudent.insert(pair(5, "Fear Kubrick"));  
        mapStudent.insert(pair(2, "Akemi Homura"));  
        mapStudent.insert(pair(-1, "Eren Jaeger"));  
        mapStudent.insert(pair(99, "lin"));  
        cout << mapStudent.size() << endl;  
        cout << endl;  
      
        ///3.     
        ///        ,         ,          map!  
        for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
            cout << iter->first << " " << iter->second << endl;  
        cout << endl;  
      
        ///4.     
        ///   3       ,    key  map ,            key      
        /// find(key)    
        iter = mapStudent.find(1);  
        if (iter != mapStudent.end())  
            cout << iter->second << endl;  
        else  
            cout << -1 << endl;  
        iter = mapStudent.find(6);  
        if (iter != mapStudent.end())  
            cout << iter->second << endl;  
        else  
            cout << -1 << endl;  
        cout << endl;  
      
        ///5.     
        ///      
        iter = mapStudent.find(1);  
        if (iter != mapStudent.end())  
            mapStudent.erase(iter);  
        cout << mapStudent.size() << endl;  
        for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
            cout << iter->first << " " << iter->second << endl;  
      
        ///      
        beg = mapStudent.find(-1);  
        end = mapStudent.find(5);  
        if (beg != mapStudent.end() && end != mapStudent.end())  
            mapStudent.erase(beg, end);///  beg end     ,   end  
            ///    end   ,     :mapStudent.erase(beg, ++end);  
            ///        end = mapStudent.upper_bound(5);  
        cout << mapStudent.size() << endl;  
        for (iter = mapStudent.begin(); iter != mapStudent.end(); iter++)  
            cout << iter->first << " " << iter->second << endl;  
        cout << endl;  
      
        ///6.        
        if (!mapStudent.empty())  
            mapStudent.clear();  
    }