Loading

[学习笔记] 语法杂学

优先队列

priority_queue<TypeName> q;
priority_queue<TypeName, Container> q;
priority_queue<TypeName, Container, Compare> q;// 分别为数据类型, 底层容器, 比较类型
//优先队列默认为大根堆,如果希望从小到大排序,则可以在比较类型上写上 greater<TypeName>
//例如
priority_queue<int, vector<int>, cmp> q;//第二个一般默认为vector

注意:不可跳过 Container 直接传入 Compare

重载运算符

常见的可以重载 \((\) \()\) 来作为自定义比较函数,放到优先队列等 STL

struct qc {
    int l, int r;
};
struct cmp {
    bool operator()(const qc& a, const qc& b) {
        return a.l < b.l || (a.l == b.l && a.r < b.r)
    }
};
priority_queue<qc, vector<qc> cmp> q;

还可以重载比较符号 (From OI Wiki)

struct student {
  string name;
  int score;
};
bool operator<(const student& a, const student& b) {
  return a.score < b.score || (a.score == b.score && a.name > b.name);
}
priority_queue<student> pq;

关于符号&取地址

运用在函数可以把虚拟数组变成实际数组

结构体构造函数用法

这部分内容来自 浅谈结构体构造函数用法

众所周知,结构题不能被初始化,以至于语法大师 JKJ 都曾提出 “结构体怎么清零?” 这样的论题

struct qc {
    string name;
    int score;
    void JacKeyJ() {
        name = "JKJ";
        score = 600;
    }
};
int main() {
    qc a;
    a.JacKeyJ();
    printf("%d\n", a.score);
}

这样显然是可以的,但是十分麻烦,如果使用结构函数可以更加简便

构造函数是一类较为特别的成员函数,它必须先声明在结构体的内部,其函数名与该结构体类型的名字一样,如此处结构体类型名为student,则构造函数的名字便为student。另外,构造函数没有返回值,不需要用户调用(用户也无法调用),而是在创建对象时自动执行

struct mat {
    int a[N][N];
    mat() {
        memset(a, 0, sizeof(a));
    }
};

上面这个可以应用于矩阵乘法

当结构体类型不同时,则可以

struct student {
    string name;
    int score;
    student (string s, int val) {
        name = s;
        score = val;
    }
};
posted @ 2022-03-27 20:06  Miraii  阅读(42)  评论(0)    收藏  举报