struct typedef enum
结构体struct
声明并初始化结构体
#include<iostream>
using namespace std;
struct student
{
int num; //学号
char name[20]; //姓名
char sex; //性别
int age; // 年龄
}stu = {123456,"John Zero",'M',19};
int main()
{
cout << stu.num << endl;
cout << stu.name << endl;
cout << stu.sex << endl;
cout << stu.age << endl;
}
如何为结构体中的字符数组赋值
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
struct happy
{
char me[10];
};
int main()
{
happy h;
strcpy(h.me, "hello");
printf("%s", h.me);
}
如果要用户输入:
int main()
{
happy h;
scanf("%s", &h.me[0]);
printf("%s", h.me);
}
可以在结构体声明时直接赋值,这样char me[]的中括号内不需要填,否则必须声明字符数组大小,否则就是没有大小的字符数组,当然不能放进去值
你想要用户自己输入可以用
struct MyStruct
{
char me[80];
};
#include <iostream>
using namespace std;
int main() {
MyStruct * my = new MyStruct();
char d;
for (int i = 0; i < 80; i++) {
cin.get(d);
my->me[i] = d;
if (d == '\n') {
break;
}
}
return 0;
}
自包含
#include<iostream>
#include<vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
int main()
{
ListNode *p = new ListNode(1);
p->next = new ListNode(2);
cout << p->val << endl;
cout << p->next->val << endl;
ListNode* q = p; //引用
q->val = 3;
q->next->val = 8;
cout << p->val << endl;
cout << p->next->val << endl;
}
输出结果:
用vector初始化链表
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
vector<int>vec = { 1,2,3,4,5 };
ListNode* head = new ListNode(vec.front());
ListNode* node = head;
for (int i = 1; i < vec.size(); i++)
{
node->next = new ListNode(vec[i]);
node = node->next;
}
for (int i = 0; i < vec.size(); i++)
{
cout << head->val << ' ';
head = head->next;
}
LeetCode:
21.合并两个有序链表
自定义数据类型typedef
typedef int age, grade;
typedef double height, weight;
age a1 = 16, a2 = 19;
height h1 = 175.3, h2 = 182.6;
cout << a1 << ' ' << h1 << ' ' << a2 << ' ' << h2;
输出结果:
16 175.3 19 182.6
枚举类型enum
enum weekday{sun=7,mon=1,tue,wed,thu,fri,sat};
int main()
{
enum gameResult{win,lose,tie,cancel};
gameResult result, omit = cancel;
for (int i = win; i <= cancel; ++i)
{
result = (gameResult)i;
if (result == omit)
cout << "游戏取消";
}
}
输出结果:
游戏取消