[] Data structure and algorithm study notes - "algorithm notes" -4

Structure

  • The basic format of the structure:
    struct the Name {
    // basic data structures, or custom data types
    };
    Eg of.
	struct studentInfo {
		int id;
		char gender;
		char name[20];
		char major[20];
	}Alice, Bob, sru[1000];
  • Not define the structure itself, but may define their own type of pointer variables
    Eg
	struct node {
		node n;//错误!!! 不能定义node型变量
		node* next;//可以定义node*型指针变量
	};
  • There are two ways to access the structure, operation, and ".", "->" Operation
    Eg
	struct studentInfo {
		int id;
		char name[20];
		studentInfo* next;
	}stu, *p;

Stu access variables, such as the wording: stu.id / stu.name / stu.next;
access pointer variable p wording elements such as:
(* p) .id / (p *) .name / (p *) .next / p-> id / p-> name / p-> next

  • Constructor initializes structure
    constructors: no need to write the return type, and the same function name and the name of the structure
	struct studentInfo {
		int id;
		char gender;
		//下面的参数用以对结构体内部变量进行赋值
		studentInfo(int _id, char _gender) {
			//赋值
			id = _id;
			gender = _gender;
		}

Or written in a row

	struct studentInfo {
		int id;
		char gender;
		//下面的参数用以对结构体内部变量进行赋值
		studentInfo(int _id, char _gender):id(_id),gender(_gender){}
	};

So when needed it can structure variable direct assignment of:

	studentInfo stu = studentInfo(10086, 'm');

However, if they redefined constructor, goes through initialization variable definition of the structure, i.e. the generated default constructor studentInfo {}
case is covered, in order not to initialize both variables on the definition of the structure, but also enjoy initialization bring convenience, you can manually add "studentInfo". This means that, as long as the number and type of parameters are not identical, can define as many constructors, to adapt to different situations initialization

Eg

	struct studentInfo {
		int id;
		char gender;
		//用以不初始化就定义结构体变量
		studentInfo(){}   //没有分号!
		//只初始化gender
		studentInfo(char _gender) {
			gender = _gender;
		}
		//同时初始化id和gender
		studentInfo(int _id, char _gender):id(_id),gender(_gender){}
	}stu,*p;

Eg

	struct Point {
		int x, y;
		Point() {}
		Point(int _x, int _y) :x(_x), y(_y) {}
	}pt[10];
	int main() 
	{
		int num = 0;
		for (int i = 1; i <= 3; i++) {
			for (int j = 1; j <= 3; j++) {
				pt[num++] = Point(i, j);
			}
		}
		for (int i = 0; i < num; i++) {
			printf("%d,%d\n", pt[i].x, pt[i].y);
		}
		return 0;
	}

Union

  • Union (also known as the Joint) is also a type of data structure, it is the different types of data are organized jointly occupy the same piece of memory, a type of data structure.

  • Type declaration union and a method similar to the structure

  • Union of keywords union

  • The general form:
    Union common name {body
    member list;
    };

  • Structures and unions to anonymously, the statement after no longer anonymous program.

  • The difference between the common structure and the body:
    the structure variable length memory is occupied by the members of accounts and a memory length, each member of each memory cell occupies their
    union variable memory occupied by the longest length is the length of the member. Address and the address of its members, i.e., a union variable is the same address.

  • Union variable references:
    the use of union variables, including the assignment, using only member variables are.
    Representation: union members variable name

  • Allowed union variables initialized for the assignment, the assignment in the program only

  • https://wenku.baidu.com/view/e2c46dfd83d049649a665848.html

Exercise
C-11.1

Title Description
complete a statistical program for candidates of votes. Suppose there are three candidates, the names are Li, Zhang and Fun. Use the name of each candidate's votes and storage structures. Record every vote votes name, the output of each candidate's final votes. Structure format may be defined as follows:
struct Person {
char name [20 is];
int COUNT;} Leader [. 3] = { "of Li", 0, "Zhang", 0, "Fun", 0};

The first line of input there is an integer n, there are n indicate the following information will be entered votes. 100 to ensure that not more than n.
After the n rows, each row contains a person's name, who votes for the ballot. To ensure that every individual names are Li, Zhang and Fun in one.

There are three lines of output, respectively, the number of votes Li, Zhang and Fun per person. First names for the output format, output followed by a colon, the final output of votes candidates.
Note that the output end of the line wrap.

  • Encounter problems
    if the if statement is written as if (namei == leader [j] .name), the program does not work properly. Solves this problem with strcmp function, guess one of the reasons is the size of the string can not be directly compared
#include <cstdio>
#include <cstring>


int main() 
{
	struct person {
		char name[20];
		int count;
	}leader[3] = { "Li",0,"Zhang",0,"Fun",0 };
	int n;
	char namei[20] = {};
	scanf("%d\n", &n);
	if (n > 100)
		return 0;
	for (int i = 0; i < n; i++)
	{
		scanf("%s", namei);
		for (int j = 0; j <= 2; j++)
		{
		//如果下面这个if语句写成if(namei==leader[j].name),程序无法正常运行。
			if (!strcmp(namei, leader[j].name))
			{
				leader[j].count ++;
			}
		}
	}
	for (int i = 0; i < 3; i++)
	{
		printf("%s:%d\n", leader[i].name, leader[i].count);
	}
	return 0;
}

11.2 C language

Title Description
definition of a structure student, the student's school number storage, name, gender and age, to read all the information for each student, save in the structure and output. Student definition of the structure as follows:
struct student {
int NUM;
char name [20 is];
char Sex;
int Age;}; The title claim pointer points to an array of structures used for input and output.

The first line of input there is an integer n, n represents the following information students will enter. Ensure that not more than n 20.
After the n rows, each row contains the corresponding student's student number, name, gender and age, separated by a space. To ensure that each individual names do not contain spaces and the length of not more than 15, sex is represented by M and F two characters.

There are n output lines, each line of output a student's student number, name, gender and age, separated by a space. Note that the output end of the line wrap.

#include <cstdio>
	#include <cstring>


	int main() 
	{
		struct student {
			int num;
			char name[20];
			char sex;
			int age;
			student(){};
		}*p,stu[20];//不可以没有stu[20]
		p = stu;//!!!看这里
		int n;
		scanf("%d\n", &n);
		for (int i = 0; i < n; i++)
		{
			//scanf("%d %s %c %d", &((p+i)->num), ((p + i)->name), &((p + i)->sex),&((p + i)->age));
			//这里要取址符!!
			scanf("%d %s %c %d", &((*(p + i)).num), (*(p + i)).name, &((*(p + i)).sex), &(( *(p + i)).age));
		}
		for (int i =0 ; i < n; i++)
		{
			printf("%d %s %c %d\n", (p + i)->num, (p + i)->name, (p + i)->sex, (p + i)->age);
			//printf("%d", ((*p).num));
		}
		return 0;
}

The above code there is a pointer written:

		for (int i = 0; i < n; i++)
		{
			scanf("%d %s %c %d", &((*p).num), (*p ).name, &((*p).sex), &(( *(p)).age));
			p++;
		}

11.4 C language

Title Description
provided data for a number of staff, which includes students and teachers. Student data include: number, name, sex, occupation, class. Teachers include: number, name, sex, occupation, job. As can be seen, the data included students and teachers are different. Now requires the data stored in the same table, the structures used to achieve union. Structure is defined as follows:
struct {
int NUM;
char name [10];
char Sex;
char job;
Union {
int class;
char position [10];
} category;}; In the above structure, if the job item as s (student), then the item 5 class (class); if the job is a term t (teacher), then the item 5 position (position).
Input data of several persons, which was stored in the array of structures that contain more than a common body, and outputs.

Input of the first row there is an integer n, the data for n less personnel n rows, respectively. N ensure that no more than 100.
N lines after each line of the content separated by a space 5. 4 before the number of the person are (integer), name (character string length does not exceed 9 without spaces), gender (character, m or f), and occupation (character, s or t). If the item 4 is s, the item 5 is an integer representing the class; if item 4 is t, the item 5 to a length of no more than a string with no spaces 9, showing position.

A total of n output lines, the same as the input format, read all content output. Note that the output end of the line wrap.

	#include <cstdio>
	#include <cstring>


	int main() 
	{ 
		struct {
			int num;
			char name[10];
			char sex;
			char job;
			union {
				int classnum;
				char position[10];
			}category;
		}sta[100],*p;
		int n;
		scanf("%d", &n);
		p = sta;
		for (int i = 0; i < n; i++)
		{
			scanf("%d %s %c %c", &((*p).num), (*p).name, &((*p).sex), &((*p).job));
			if (((*p).job) == 's') scanf("%d", &((*p).category.classnum));
			else if (((*p).job) == 't') scanf("%s", ((*p).category.position));
			p++;
		}
		p = sta;
		for (int i = 0; i < n; i++)
		{
			printf("%d %s %c %c ",((*p).num), (*p).name, ((*p).sex),((*p).job));
			if (((*p).job) == 's') printf("%d\n", ((*p).category.classnum));
			else if (((*p).job) == 't') printf("%s\n", ((*p).category.position));
			p++;
		}
		return 0;
}

11.7 C language

Description Title
write two input functions and print, respectively, 5 for inputting student data record and print five student records. For each student, whose records contain a student number, name, score a total of three courses of five. And input with the master function calls the print function input and output, respectively.
Requires the use of an array of structures to achieve, it comprises a structural body 5 each student records.

Enter the total of five lines, each containing a student's student number (integer), the name (no spaces string length does not exceed 19) and three course grades (an integer between 0 and 100), separated by a space .

The same input and output format, each line of output of all records of a student. Note that the output end of the line wrap.

#include <cstdio>
#include <cstring>

struct student {
	char name[10];
	int num;
	int score[3];
}stu[5], *p;

void input(student* stu)
{
	p = stu;
	for (int i = 0; i < 5; i++)
	{
		scanf("%d %s",  &((*p).num),(*p).name);
		for (int j = 0; j < 3; j++)
			scanf("%d", &((*p).score[j]));
		p++;
	}
}

void output(student * stu)
{
	p = stu;
	for (int i = 0; i < 5; i++)
	{
		printf("%d %s ", (*p).num, (*p).name);
		for (int j = 0; j < 3; j++)
		{
			printf("%d ", (*p).score[j]);
			if (j == 2) printf("\n");
		}
		p++;
	}
}

int main() 
{ 
	p = stu;
	input(p);
	p = stu;
	output(p);
	return 0;
}

11.8 C language

Title Description
There are 10 students, each student achievement data, including number, name, three courses. These 10 students read data output requires an overall average score of three courses, as well as the highest average student's personal data (including student number, name, three course grade, the average score).

Enter the
total of 10 rows, each row containing a student's student number (integer), the name (no spaces string length does not exceed 19) and three course grades (an integer between 0 and 100), separated by a space .

Output The first line contains three real numbers represent the total average score of three courses, 2 decimal places, the output of a space after each number.
The second line of the highest student average output of personal data, the input data in the same format. If there are a number of individual student data the highest average student, according to the input output highest score of the first order.
Note that the output end of the line wrap.

#include <cstdio>
#include <cstring>

struct student {
	char name[10];
	int num;
	int score[3];
}stu[10], *p;

void input(student* stu)
{
	p = stu;
	for (int i = 0; i < 10; i++)
	{
		scanf("%d %s",  &((*p).num),(*p).name);
		for (int j = 0; j < 3; j++)
			scanf("%d", &((*p).score[j]));
		p++;
	}
}

void output1(student * stu)
{
	for (int i = 0; i < 3; i++)
	{
		double sum = 0;
		p = stu;
		for (int j = 0; j < 10; j++)
		{
			sum += p->score[i];
			p++;
		}
		printf("%.2lf ", (double)(sum/10));
	}
	printf("\n");
}

void output2(student* stu)
{
	p = stu;
	double sco[10] = {0},maxsco=0;
	int maxnum;
	for (int i = 0; i < 10; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			sco[i] += p->score[j];
		}
		sco[i] = (double)(sco[i] / 10);
		if (sco[i] > maxsco)
		{
			maxsco = sco[i];
			maxnum = i;
		}
		p++;
	}
	p = stu + maxnum;
	printf("%d %s ", (*p).num, (*p).name);
	for (int j = 0; j < 3; j++)
	{
		printf("%d ", (*p).score[j]);
	}
}

int main() 
{ 
	p = stu;
	input(p);
	p = stu;
	output1(p);
	p = stu;
	output2(p);
	return 0;
}
Published 43 original articles · won praise 4 · Views 1223

Guess you like

Origin blog.csdn.net/weixin_42176221/article/details/99709160