讲题主要通俗易懂,略有不妥,还请见谅。(0基础也保证看得懂)
结构体的基本概念
结构体(struct)顾名思义就是自己定的一个结构,例如常见的结构有:int , double, short, long long, flaot······对吧。这里的结构就是你自己的结构名。
我们先来看一下结构体的创建方法:
struct structname(随便你怎么取){
type(int, double, long······) typename(自己发挥)
// 如果你想要在这里加一点函数也可以
};
我们暂定结构名是student,表示学生信息,这样好理解:
struct student{
string name;
int age;
};
没有问题吧!
那怎么访问呢?
#include <bits/stdc++.h>
using namespace std;
struct student{
string s;
int age;
};
int main()
{
ios::sync_with_stdio(false),cin.tie(0);
student Student;
cin >> Student.s >> Student.age;
cout << Student.s << ' ' << Student.age;
return 0;
}
你就把他当成 int 来用 int 后面要跟一个变量名对吧!那我们这个结构体后面也要跟一个名字。
Studnet . s 是什么意思?' . ' 表示访问成员函数。 就是变量的意思 , 再想一下 string不是也有
string s ; s . size(); 这里size(),就是string 这个结构的成员函数。
懂了吗?
那换一种想法 int 后面是不是可以加 数组名,结构体也一样:
#include <bits/stdc++.h>
using namespace std;
struct student{
string s;
int age;
};
int main()
{
ios::sync_with_stdio(false),cin.tie(0);
int n;
cin >> n;
student Student[n];
for(int i = 0; i < n; i++){
cin >> Student[i].s >> Student[i].age;
cout << Student[i].s << ' ' << Student[i].age << '\n';
}
return 0;
}
我们懂了这个后,下一个讲student {} 后面那个分号干什么?
我们把刚刚那个代码换一种写法:
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false),cin.tie(0);
int n;
cin >> n;
struct student{
string s;
int age;
}Student[n];
for(int i = 0; i < n; i++){
cin >> Student[i].s >> Student[i].age;
cout << Student[i].s << ' ' << Student[i].age << '\n';
}
return 0;
}
在这个基础上我们再来讲一下结构体与容器的融合升华。
vector<int> 是不是对的, 那vector<student> 是不也是对的。
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false),cin.tie(0);
int n;
cin >> n;
struct student{
string s;
int age;
};
vector<student> Student(n);
for(int i = 0; i < n; i++){
cin >> Student[i].s >> Student[i].age;
cout << Student[i].s << ' ' << Student[i].age << '\n';
}
return 0;
}
我们下期再见。
下期预告:
下次我们会讲结构体函数与结构函数,析构函数。