河北大学程序设计训练营

[TOC]

C++ 引用 & 与传值的区别

  • c++ & 被称为引用符号(函数参数列表使用)
  • c语言 & 被称为取地址运算符

函数传参 int a 是传递a的值 进行函数运算

使用引用变量 int &a 是直接对变量本身进行操作

## 引用& 例子

引用

1
2
3
4
5
6
7
8
void func(int &a) {
// 传⼊入的是n的引⽤用,相当于直接对n进⾏行行了了操作,只不不过在func函数中换了了个名 字叫a
a = 99;
}
int main() {
int n = 0;
func(n); // n由0变成了99
}

传值

1
2
3
4
5
6
7
8
void func(int a) {
// 传入的是0这个值,并不会改变main函数中n的值
a = 99;
}
int main() {
int n = 0;
func(n);// 并不会改变n的值,n还是0
}

C++ struct

c++ 和 c 语言一样,但是 c++ 可以 可以省略 struct 关键字 直接使用

代码样例

1
2
3
4
5
6
struct stu {
int grade;
float score;
};
struct stu arr1[10];// C语⾔兼容
stu arr2[10];// C++ 特有省略

C++ sort

头文件 #include<algorithm>

c++ 的默认计算相关的类集合

  • sort
  • swap
  • max
  • min

sort使用时

一般使用在结构体 容器向量排序

1
2
3
4
#include <iostream> 
#include <vector>
#include <algorithm>
using namespace std;

万能文件头 #include<bits/stdc++.h>

一次调用 全部引用 但是学习期间还是推荐 单独引用

sort使用

语法

Sort(start,end,cmp);

参数

(1)start 表示要排序数组的起始地址;
(2)end 表示数组结束地址的下一位;
(3)cmp 用于规定排序的方法,可不填,默认升序。

代码样例

  • cmp 只能使用 大于 或 小于 进行返回 因为他底层的实现 原理是 快速排序 若使用小于等于或大于等于进行判断 可能 会使指针 不断右移 发生段错误
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(int a, int b) { // cmp函数返回的值是bool类型
return a > b;// 从大到小排列列
}
int main() {
vector<int> v(10);
for (int i = 0; i < 10; i++) {
cin >> v[i];
}
sort(v.begin(), v.end());
// 默认从小到大排序
int arr[10];
for (int i = 0; i < 10; i++) {
cin >> arr[i];
}
sort(arr, arr + 10, cmp);
// 使用cmp自动排序,从大到小
return 0;
}

综合使用 struct 和 sort 的例题

7-8-1 sort 德才论

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct node {
int num, de, cai;
};
int cmp(struct node a, struct node b) {
if ((a.de + a.cai) != (b.de + b.cai))
return (a.de + a.cai) > (b.de + b.cai);
else if (a.de != b.de)
return a.de > b.de;
else
return a.num < b.num;
}
int main() {
int n, low, high;
scanf("%d %d %d", &n, &low, &high);
vector<node> v[4];
node temp;
int total = n;
for (int i = 0; i < n; i++) {
scanf("%d %d %d", &temp.num, &temp.de, &temp.cai);
if (temp.de < low || temp.cai < low)
total--;
else if (temp.de >= high && temp.cai >= high)
v[0].push_back(temp);
else if (temp.de >= high && temp.cai < high)
v[1].push_back(temp);
else if (temp.de < high && temp.cai < high && temp.de >= temp.cai)
v[2].push_back(temp);
else
v[3].push_back(temp);
}
printf("%d\n", total);
for (int i = 0; i < 4; i++) {
sort(v[i].begin(), v[i].end(), cmp);
for (int j = 0; j < v[i].size(); j++)
printf("%d %d %d\n", v[i][j].num, v[i][j].de, v[i][j].cai);
}
return 0;
}