Home>

C++ structure array

A structure variable can store a set of data (such as a student's student number, name, grade, etc.). If the data of 10 students need to participate in the calculation,Obviously an array should be used,This is the structure array.Structure arrays are different from the numerical arrays previously introduced in that each array element is a structure type data.They all include individual members.

Defining structure arrays is similar to defining structure variables.When defining an array of structures, simply declare it as an array.Such as:

struct student //declares the structure type student
{
  int num;
  char name [20];
  char sex;
  int age;
  float score;
  char addr [30];
};
student stu [3];//define array stu of type student

You can also directly define an array of structures,Such as:

struct student
{
  int num;
  char name [20];
  char sex;
  int age;
  float score;
  char addr [30];
} stu [3];

or

struct
{
  int num;
  char name [20];
  char sex;
  int age;
  float score;
  char addr [30];
} stu [3];

Structure arrays are initialized like other types of arrays.The structure array can be initialized.Such as:

struct student
{
  int num;
  char name [20];
  char sex;
  int age;
  float score;
  char addr [30];
} stu [3]={
  {10101, "li lin", 'm', 18,87.5, "103 beijing road"},  {10102, "zhang fun", 'm', 19,99, "130 shanghai road"},  {10104, "wang min", 'f', 20,78.5, "1010 zhongshan road"}
};

When defining an array stu, the number of elements may not be specified.That is written as:

 stu []={{…}, {…}, {…}};

When compiling, the system will determine the number of array elements according to the number of structure constants given the initial value.A structure constant should include the values ​​of all members in the structure.

Of course, the initialization of the array can also take the following form:

 student stu []={{…}, {…}, {…}};//Structure type student has been declared in advance

As can be seen from the above,The general form of structure array initialization is to add={initial value table column} after the defined array name;

Structure array application example

Here is a simple example to illustrate the definition and reference of the structure array.

[Example] Statistical procedures for obtaining votes for candidates.With 3 candidates,In the end, only one person was elected as the leader.There are 10 people voting today,Enter the names of these 10 candidates from the keyboard,It is required to output the voting results of these 3 candidates at the end.

Can define an array of candidate structures,Includes 3 elements, and stores related data in each element.The procedure is as follows:

#include<iostream>
using namespace std;
struct person //Declares the structure type person
{
  char name [20];
  int count;
};
int main ()
{
  //Define an array of type person,Contents of the names of the 3 candidates and the current number of votes obtained
  person leader [3]={"li", 0, "zhang", 0, "fun", 0};
  int i, j;
  char leader_name [20];//leader_name is the name of the person selected by the voter
  for (i=0;i<10;i ++)
  {
   cin>>leader_name;//Enter the names written on the 10 tickets
   for (j=0;j<3;j ++) //Compare the names on the ticket with the names of the 3 candidates
     //If the name is the same as a candidate,Give him a vote
     if (strcmp (leader_name, leader [j] .name) == 0) leader [j] .count ++;
  }
  cout<endl;
  for (i=0;i<3;i ++) //Output the names of the 3 candidates and the final votes
  {
   cout<leader [i] .name<<<<<leader [i] .count<<endl;
  }
  return 0;
}

The operation is as follows:

zhang↙ (enter the name of one candidate at a time)
li↙
fun↙
li↙
zhang↙
li↙
zhang↙
li↙
fun↙
wang↙
li:4 (output the names of the 3 candidates and the final votes)
zhang:3
fun:2

The program defines a global structure array leader, which has 3 elements, each element contains two members,Name (name) and count (count of votes). Initialize the array when it is defined,Zero the votes of all three candidates.

In this example,You can also use a string variable of the string method instead of a character array to store name data.The program can be modified as follows:

#include<iostream>
#include<string>
using namespace std;
struct person
{
string name;//member name is a string variable
int count;
};
int main ()
{
person leader [3]={"li", 0, "zhang", 0, "fun", 0};
int i, j;
string leader_name;//leader_name is a string variable
for (i=0;i<10;i ++)
{
cin>>leader_name;
for (j=0;j<3;j ++)
if (leader_name == leader [j] .name) leader [j] .count ++ //Compare with "=="
}
cout<endl;
for (i=0;i<3;i ++)
{
cout<leader [i] .name<<<<<
}
return 0;
}

The operation is the same as before.A program then saves memory space,More convenient to use,Better legibility.However, some C++ systems cannot initialize structure variables that contain string members.Requires some modifications to run, Readers can try it on the computer.

C++ pointer to structure variable

The pointer of a structure variable is the starting address of the memory segment occupied by the variable.You can set a pointer variable,Used to point to a structure variable,The value of this pointer variable is the starting address of the structure variable.Pointer variables can also be used to point to elements in a structure array.

Refer to members in a structure variable by a pointer to a structure variable

The following uses a simple example to illustrate the application of pointer variables to structure variables.

[Example] Application of a pointer to a structure variable.

#include<iostream>
#include<string>
using namespace std;
int main ()
{
  struct student //declaration structure type student
  {
   int num;
   string name;
   char sex;
   float score;
  };
  student stu;//Define a variable of type student
  student * p =&stu;//Define p as a pointer variable to student data and point to stu
  stu.num=10301;//Assign values ​​to members in stu
  stu.name="wang fun";//Can directly assign values ​​to string variables
  stu.sex="f";
  stu.score=89.5;
  cout<stu.num<"<<stu.name<<""<stu.sex<"""<<<
  stu.score<endl;
  cout<p->num<"<<(* p) .name<<<<<<(* p) .sex<<<<p) .score<endl;
  return 0;
}

The program results are as follows:

10301 wang fun f 89.5 (reference member by structure variable name)

10301 wang fun f 89.5 (refer to members in structure variables through pointers)

The output of the two cout statements is the same.

For ease of use and to make it intuitive,C++ provides an operator->that points to a structure variable, for example, p->num represents the member num in the structure variable that pointer p currently points to.

p->num and (* p) .num are equivalent.

same

p->name is equivalent to (* p) .name.

That is,The following three forms are equivalent:

Structure variables.Member name. Such as stu.num.

(* p). Member name. Such as (* p) .num.

p->member name. Such as p->num.

"->" is called a pointing operator.

Please analyze the following operations:

p->n gets the value of member n in the structure variable pointed to by p. p->n ++ gets the value of member n in the structure variable pointed to by p, and increments it by using it. ++ p->n gets the value of member n in the structure variable pointed to by p and increments it before using it.

Form a linked list with structure variables and pointers to structure variables

Linked lists are a common important data structure.The following figure shows the structure of the simplest type of linked list (one-way linked list).

The linked list has a "head pointer" variable, which is represented by head in the figure, and it stores an address.The address points to an element.Each element in the linked list is called a "node", and each node should include two parts:

The first is the actual data that the user needs.

The second is the address of the next node.

It can be seen that the storage units of the elements in the linked list in memory may be discontinuous.Looking for an element,You can find the previous element first,Find the next element based on the next element address it provides.

can be seen,The data structure of this linked list,You must use structure variables and pointers to achieve this.

Can declare a struct type,Contains two members,One is the actual data the user needs,The other is a pointer variable used to store the address of the next node.

For example, you can design such a structure type:

struct student
{
  int num;
  float score;
  student * next;//next points to the student structure variable
};

The members num and score are the data the user needs,Corresponds to a, b, c, d in the node in Figure 7.8. next is a member of pointer type,It points to student type data (that is, the type of structure where next is located). In this way, a linked list can be created.See picture.

Each node in the graph belongs to the student type, and the address of the next node is stored in its member next.The programmer does not need to know the specific address of each node.Just make sure that the address of the next node can be placed in the member next of the previous node.

Here is an example to illustrate how to build and output a simple linked list.

[Example] Create a simple linked list as shown in the figure,It consists of three nodes of student data.Output the data in each node.

#define null 0
#include<iostream>
using namespace std;
struct student
{
  long num;
  float score;
  struct student * next;
};
int main ()
{
  student a, b, c, * head, * p;
  a. num=31001;
  a.score=89.5;//Assign the num and score members of node a
  b. num=31003;
  b.score=90;//Assign the num and score members of node b
  c. num=31007;
  c.score=85;//Assign the num and score members of node c
  head =&a;//Assign the starting address of node a to the head pointer head
  a.next =&b;//Assign the starting address of node b to the next member of node a
  b.next =&c;//Assign the starting address of node c to the next member of node b
  c.next=null;//The next member of the node does not store other node addresses
  p=head;//Make p pointer point to a node
  do
  {
   cout<<p->num<"<<p->score<<endl;//output data for the node pointed to by p
   p=p->next;//make p point to the next node
  } while (p!=null);//The value of p after the output of node c is null
  return 0;
}

This example is relatively simple.All nodes (structure variables) are defined in the program,It ’s not temporary.It ca n’t be released after use,This linked list is called a static linked list.Each node can be accessed through the next pointer of the previous node.You can also directly access the structure variable names a, b, and c.

Dynamic linked list means that each node can be inserted and deleted at any time.These nodes do not have variable names.You can only find the previous node first,In order to find the next node based on the address of the next node it provides.Only the address of the first node is provided,That is, the head pointer can access the entire linked list.Like an iron chain,Buckle one ring,The middle cannot be disconnected.

Build a dynamic linked list,The operator new to dynamically allocate memory and the operator delete to delete memory are used later.

c
  • Previous Detailed PHP regular expression replacement implementation (PHP preg_replace, PHP preg_replace)
  • Next Detailed sqlserver query table index