- yuxitong's blog
结构体!
- 2023-9-26 13:13:26 @
结构体!
结构体的定义
众所周知,在C++里面有一些内置数据结构(int, char, string, double)但是,在做题的时候,总是需要多个数据绑定在一起,这个时候,就需要用到结构体(struct)。
结构体是C语言中一种重要的数据类型,该数据类型由一组称为成员的数据所组成,其中 每个成员可以是不同类型的 。结构体通常用来表示类型不同但是又相关的若干数据。(注意:数组与结构体一样,也是一种值的集合,只不过数组的每个元素都要是相同类型的,而结构体的每个成员可以是不同类型的)
结构体的使用
结构体的定义
struct score{
int math; //分号!
int english;
}; //分号,分号!
struct student{
string name;
int number;
int age;
struct score; //结构体与结构体之间可以嵌套
};
结构体的使用:
//顶级垃圾程序
//A very bad program
#include <bits/stdc++.h>
using namespace std;
struct score{
int chinese;
int math; //分号!
int english;
}; //分号,分号!
struct student{
string name;
int number;
int age;
score num; //结构体与结构体之间可以嵌套
};
score a;
student b;
int main(){
a.chinese = 95;
a.english = 100;
cout << a.chinese << endl;
a.math = a.chinese + a.english;
cout << a.math << endl;
b.num.math = 100;
cout << b.num.math << endl;
return 0;
}
结构体函数的编辑:
//顶级垃圾程序
//A very bad program
#include <bits/stdc++.h>
using namespace std;
struct Stack{
public:
int a[100];
int t = 0;
void push(int n){
a[t] = n;
t++;
}
void pop(){
t--;
}
int top(){
return a[t - 1];
}
bool empty(){
if (t == 0) return true;
return false;
}
};
Stack stk;
int main(){
int n, m;
cin >> n >> m;
stk.push(n);
stk.push(m);
cout << stk.top() << endl;
stk.pop();
cout << stk.top() << endl;
stk.pop();
cout << stk.empty() << endl;
return 0;
}