c++之中结构体中.和->以及结构体sort排序

tech2022-08-06  117

1 结构体中.和->的用法

定义结构体指针,访问成员时就用-> 定义结构体变量,访问成员时就用.

例如: struct A { int a; char b; };

struct A q; 访问成员就用:q.a; struct A *p; 访问成员就用:p->a;

#include"stdio.h" #include"stdlib.h" struct linkwqf{ int age; char * name; struct linkwqf* next; }; struct linkwqf linkwww1;/*第一种声明结构体类型变量的方法 这种方法意义不大*/ typedef struct linkwqf linkwww2;/*第一种声明结构体类型变量的方法*/ void main(void) { struct linkwqf lin1;/*声明结构体变量*/ struct linkwqf *lin2;/*声明指向结构体的指针 后面我分配内存空间*/ lin1.age=12;/*用.来取得结构体里面的变量*/ lin1.name="wqf";/*用.来取得结构体里面的变量*/ printf("1---age=%d,name=%s\n",lin1.age,lin1.name); lin2=(linkwww2*)malloc(sizeof(linkwww2));/*要分配内存空间*/ lin2->age=21;/*用->来取得结构体变量*/ lin2->name="wangkt";/*用->来取得结构体的变量*/ printf("2---age=%d,name=%s\n",lin2->age,lin2->name); printf("safsdfasdfasdfasd\n"); }

2 结构体中使用构造函数初始化

struct My{ int first; char c; My(){ first = 10; c = 'T'; } }; struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} };

不适用于c语言结构体。

3 结构体sort排序

在对结构体数组排序时,首先确定排序数组的关键字,并且在排序过程中不是交换关键字的顺序,而是交换这个结构的地址,从而使结构体数组有序。

#include <iostream> using namespace std; #include <algorithm> typedef struct Test { int a; int b; }t; t test[100]; bool Cmpare(const t &a, const t &b) { return a.a < b.a; } int main() { sort(test, test+ 100,cmpare); return 0; }
最新回复(0)