• set and map


    SET

    一个集合(set)是一个容器,它其中所包含的元素的值是唯一的。这在收集一个数据的具体值的时候是有用的。集合中的元素按一定的顺序排列,并被作为集合中的实例。如果你需要一个键/值对(pair)来存储数据,map是一个更好的选择。一个集合通过一个链表来组织,在插入操作和删除操作上比向量(vector)快,但查找或添加末尾的元素时会有些慢。

      下面是一个例子:

    //程序:set演示
    //目的:理解STL中的集合(set)

    #include <string>
    #include <set>
    #include <iostream>
    using namespace std;

    int main(int argc, char* argv[])
    {
    set <string> strset;
    set <string>::iterator si;
    strset.insert("cantaloupes");
    strset.insert("apple");
    strset.insert("orange");
    strset.insert("banana");
    strset.insert("grapes");
    strset.insert("grapes");
    for (si=strset.begin(); si!=strset.end(); si++)
    { cout << *si << " "; }
    cout << endl;
    return 0;
    }

    // 输出: apple banana cantaloupes grapes orange
    //注意:输出的集合中的元素是按字母大小顺序排列的,而且每个值都不重复。

    MAP

    Map是一个通过key(键)来获得value(值)的模板类。

      另一个问题是你希望在map中使用自己的类而不是已有的数据类型,比如现在已经用过的int。建立一个“为模板准备的(template-ready)”类,你必须确保在该类中包含一些成员函数和重载操作符。下面的一些成员是必须的:

      缺省的构造函数(通常为空)

      拷贝构造函数

      重载的”=”运算符

      你应该重载尽可能多的运算符来满足特定模板的需要,比如,如果你想定义一个类作为 map中的键(key),你必须重载相关的运算符。但在这里不对重载运算符做过多讨论了。

    //程序:映射自定义的类。
    //目的:说明在map中怎样使用自定义的类。

    #include <string>
    #include <iostream>
    #include <vector>
    #include <map>
    using namespace std;

    class CStudent
    {
     public :
      int nStudentID;
      int nAge;
     public :
      //缺省构造函数——通常为空
      CStudent() { }
      // 完整的构造函数
      CStudent(int nSID, int nA) { nStudentID=nSID; nAge=nA; }
      //拷贝构造函数
      CStudent(const CStudent& ob)
      {
       nStudentID=ob.nStudentID; nAge=ob.nAge; }
      // 重载“=”
      void operator = (const CStudent& ob)
      {
       nStudentID=ob.nStudentID; nAge=ob.nAge;
      }
    };

    int main(int argc, char* argv[])
    {
     map <string, CStudent> mapStudent;

     mapStudent["Joe Lennon"] = CStudent(103547, 22);
     mapStudent["Phil McCartney"] = CStudent(100723, 22);
     mapStudent["Raoul Starr"] = CStudent(107350, 24);
     mapStudent["Gordon Hamilton"] = CStudent(102330, 22);

     // 通过姓名来访问Cstudent类中的成员
     cout << "The Student number for Joe Lennon is " <<
     (mapStudent["Joe Lennon"].nStudentID) << endl;

     return 0;
    }

    zjfc----1116 {A}+{B}

    Code
  • 相关阅读:
    如何判断网页中引入jquery
    回车事件jquery
    bootcss
    jquery 固定导航
    vs2012常用快捷键总结
    网页上新闻,多余内容用....(省略号)代替
    git的使用
    vue获取点击事件源的方法
    JS实现复制功能
    AdminLTE 学习笔记
  • 原文地址:https://www.cnblogs.com/pandy/p/1447344.html
Copyright © 2020-2023  润新知