zoukankan      html  css  js  c++  java
  • <STL> 容器混合使用

    1. 定义一个表示学生的结构(Student),其中包含一个名字(string)和一个分数(total)

    2.用一个索引值(随便一个整数)和一个结构(Student)来构造pair<int,Student>

    3.用pair<int,Student>作为set容器的插入元素。

    这里要了解的是,这里插入到set容器的元素(pair<int,Student>)是我自定义的,因此需要定义针对pair<int,Student>进行比较大小的函数,方能插入set容器中,因为set容器是有序的。其他的就不需要解释了,直接看代码...

    #include <iostream>
    #include
    <utility> // 使用pair<>
    #include <string>
    #include
    <set>
    using namespace std;

    struct Student{
    string name;
    int total;
    friend ostream
    & operator<<(ostream& os,const Student& st)
    {
    os
    <<st.name<<" "<<st.total<<endl;
    return os;
    }
    };
    bool operator<(const pair<int,Student>& p1,const pair<int,Student>& p2) // 给出pair<int,Student>类型的比较函数
    {
    return p1.first<p2.first;
    }
    int main()
    {
    Student student[
    2]={
    {
    "hicjiajia",427},
    {
    "abcdefghi",429}
    };
    pair
    <int,Student> p1(31,student[0]); // 定义两个pair<int,Student>对象
    pair<int,Student> p2(21,student[1]); // 定义两个pair<int,Student>对象

    set<pair<int,Student> > ss; //pair<int,Student>类型作为set容器的插入类型
    ss.insert(p1);
    ss.insert(p2);

    set<pair<int,Student> >::iterator it=ss.begin();
    for (; it!=ss.end(); it++)
    //cout<<(*it).first<<" "<<(*it).second.name<<" "<<(*it).second.total<<endl;
    cout<<(*it).first<<" "<<(*it).second<<endl; //输出结果,输出(*it).second元素时会调用Student的operator<<()函数进行输出
    system("pause");
    return 0;
    }

     注意:在Student结构中,我重写了operator<<(),以方便输出,请注意第二个参数的类型要为 const &,我一开始写的是Student& 总是报错,后来试着改成const Student& 就OK了,不知道为什么,可能是我C++没学得好吧...

  • 相关阅读:
    Kafka原理与java simple producer示例
    【转载】kafka的工作原理
    Python 基本类型转换
    hadooop2.6 job pending research
    记一次zookeeper集群搭建错误的排除
    Apache Drill Install and Test
    Linux或Unix环境利用符号链接升级Maven
    Android之Linearlayouy线性布局
    Effective Java Second Edition --- Builder Pattern
    java生产者/消费者模式实现——一生产者一消费者(操作值)
  • 原文地址:https://www.cnblogs.com/hicjiajia/p/1910042.html
Copyright © 2011-2022 走看看