Home>

c++ one-dimensional array

Defining a one-dimensional array

The general format for defining a one-dimensional array is:

Type identifier array name [constant expression];

E.g:

 int a [10];

It means that the array name is a, this array is an integer,There are 10 elements.

A few notes about one-dimensional arrays:

1) The rules for naming arrays are the same as for variable names.Follow the rules for identifier naming.

2) A constant expression enclosed in square brackets indicates the subscript value,Such as the following is legal:

 int a [10];
  int a [2 * 5];
  int a [n * 2];//Assuming n has been defined as a constant variable

3) The value of the constant expression represents the number of elements,That is the length of the array.For example, in "int a [10];", 10 indicates that the a array has 10 elements, and the index starts from 0. The 10 elements are:a [0], a [1], a [2], a [3], a [4], a [5], a [6], a [7], a [8], a [9]. Note that the last element is a [9] instead of a [10].

4) Constant expressions can include constants, constant variables, and symbolic constants.You cannot include variables.That is,C++ does not allow dynamic definition of the size of the array,That is, the size of the array does not depend on the value of the variable during the running of the program.For example, defining an array like this would not work:

 int n;
  cin>>n;//Enter the length of the a array
  int a [n];//Attempt to determine the length of the array based on the value of n

It would be legal to change lines 1 and 2 to the following:

 const int n=5;

References the elements of a one-dimensional array

The array must be defined first,Then use.You can only reference the values ​​of array elements one by one, not the values ​​of all elements in the entire array at once.

The array elements are represented as:

Array name [subscript]

Subscripts can be integer constants or integer expressions.E.g:

 a [0]=a [5] + a [7]-a [2 * 3]

[Example] A reference to an array element.

#include<iostream>
using namespace std;
int main ()
{
  int i, a [10];
  for (i=0;i<= 9;i ++)
   a [i]=i;
  for (i=9;i>= 0;i--)
   cout<a [i]<<""
  cout<endl;
  return 0;
}

The results are as follows:

9 8 7 6 5 4 3 2 1 0

The program makes the values ​​of a [0] ~ a [9] 0 ~ 9, and then outputs them in reverse order.

One-dimensional array initialization

1) Assign initial values ​​to the array elements when defining the array.E.g:

 int a [10]={0,1,2,3,4,5,6,7,8,9};

2) You can assign values ​​to only some elements.E.g:

 int a [10]={0,1,2,3,4};

3) If i want all elements in an array to be 1, you can write:

 int a [10]={1,1,1,1,1,1,1,1,1,1};

Cannot be written as

 int a [10]={1 * 10};

You cannot assign an initial value to the entire array.

4) When assigning initial values ​​to all array elements,It is not necessary to specify the array length.E.g:

 int a [5]={1,2,3,4,5};

Can be written as

 int a []={1,2,3,4,5};

Example of one-dimensional array program

[Example] Use arrays to solve the problem of finding fibonacci sequences.

You can use 20 elements to represent 20 numbers in a sequence, starting with the third number,You can directly find the numbers with the expression f [i]=f [i-2] + f [i-1].The procedure is as follows:

#include<iostream>
#include<iomanip>
using namespace std;
int main ()
{
  int i;
  int f [20]={1,1};//f [0]=1, f [1]=1
  for (i=2;i<20;i ++)
   f [i]=f [i-2] + f [i-1];//When the value of i is 2, f [2]=f [0] + f [1], and so on
  for (i=0;i<20;i ++) //The function of this loop is to output 20 numbers
  {
   if (i%5 == 0) cout<< endl;//Control line feed,Output 5 data per line
   cout<setw (8)<f [i];//Each data column takes up 8 columns width
  }
  cout<endl;//Last line feed
  return 0;
}

The results are as follows:

[Example] Write a program,Sort the 10 numbers using the bubble method (in ascending order).

The idea of ​​the bubble method is:compare two adjacent numbers,Turn the small one to the front.See Figure 5.2. Then perform the second comparison and compare the remaining five numbers according to the above method.See picture.

It can be inferred thatIf there are n numbers, n-1 comparisons (and exchanges) are performed. In the first pass, we will make n-1 pairwise comparisons.In the jth pass, n-j pairwise comparisons are performed.

Write a program based on the above ideas,Let n=10. This example defines the length of the array as 11. A [0] is not used, only a [1] ~ a [10] are used to meet people's habits.From the previous description,There should be 9 comparisons and exchanges.

#include<iostream>
using namespace std;
int main ()
{
  int a [11];
  int i, j, t;
  cout<"input 10 numbers:"<endl;
  for (i=1;i<11;i ++) //Enter a [1] ~ a [10]
   cin>>a [i];
  cout<endl;
  for (j=1;j<= 9;j ++) //Compare 9 times
   for (i=1;i<= 10-j;i ++) //(10-j) pairwise comparisons in each pass
     if (a [i]>a [i + 1]) //If the previous number is greater than the latter number
     {
      t=a [i];a [i]=a [i + 1];a [i + 1]=t;
     } //Swap the positions of two numbers, Float up
  cout<"the sorted numbers:"<endl;
  for (i=1;i<11;i ++) //output 10 numbers
   cout<a [i]<<""
  cout<endl;
  return 0;
}

The operation is as follows:

input 10 numbers:
3 5 9 11 33 6 -9 -76 100 123↙
the sorted numbers:
-76 -9 3 5 6 9 11 33 100 123

c++ two-dimensional array

An array with two indices is called a two-dimensional array.Some data depend on two factors to be uniquely determined,For example, there are 3 students, each student has a grade of 4 courses,Obviously, the performance data is a two-dimensional table.As shown in the table in the book.

Want to show the result of the 4th course of the 3rd student,It is necessary to point out the two factors of the student's serial number and the course serial number.It is expressed mathematically as s3,4. In C++ it is represented by s [3] [4], which represents the data 73.

Defining a two-dimensional array

The general form for defining a two-dimensional array is:

Type identifier array name [constant expression] [constant expression];

E.g:

 float a [3] [4], b [5] [10];

Define a as a 3 × 4 (3 rows and 4 columns) single-precision array,b is a 5 × 10 (5 rows and 10 columns) single-precision array.Note that it cannot be written as "float a [3,4], b [5,10];". C++ uses this definition for two-dimensional arrays,Let us think of a two-dimensional array as a special one-dimensional array:its elements are again a one-dimensional array.For example, you can think of a as a one-dimensional array,It has 3 elements:a [0], a [1], a [2], and each element is a one-dimensional array containing 4 elements,See Figure 5.4. a [0], a [1], a [2] are the names of three one-dimensional arrays.

The two-dimensional array defined above can be understood as defining three one-dimensional arrays.That is equivalent to:

 float a [0] [4], a [1] [4], a [2] [4];

Here a [0], a [1], a [2] are used as one-dimensional array names.C++ 's processing method is very convenient when the array is initialized and represented by a pointer.This will be realized later.

In C++, the order of elements in a two-dimensional array is:stored in rows,That is, the elements of the first row are stored in memory first.Then store the elements of the second line.The figure shows the storage order of the a [3] [4] array.

The two-dimensional array defined above can be understood as defining three one-dimensional arrays.That is equivalent to:

 float a [0] [4], a [1] [4], a [2] [4];

Here a [0], a [1], a [2] are used as one-dimensional array names.C++ 's processing method is very convenient when the array is initialized and represented by a pointer.This will be realized later.

In C++, the order of elements in a two-dimensional array is:stored in rows,That is, the elements of the first row are stored in memory first.Then store the elements of the second line.Figure 5.5 shows the storage order of the a [3] [4] array.

C++ allows the use of multidimensional arrays.With the foundation of a two-dimensional array,It is not difficult to master multidimensional arrays.For example, to define a three-dimensional array:

float a [2] [3] [4];

Define a float-type three-dimensional array a, which has 2 × 3 × 4=24 elements. The order of multi-dimensional array elements in memory:the index of the first dimension changes most slowly,The rightmost subscript changes fastest.For example, the order of the elements of the above three-dimensional array is:

a [0] [0] [0] → a [0] [0] [1] → a [0] [0] [2] → a [0] [0] [3] → a [0] [1 ] [0] → a [0] [1] [1] → a [0] [1] [2] → a [0] [1] [3] → a [0] [2] [0] → a [0] [2] [1] → a [0] [2] [2] → a [0] [2] [3] → a [1] [0] [0] → a [1] [0] [1] → a [1] [0] [2] → a [1] [0] [3] → a [1] [1] [0] → a [1] [1] [1] → a [ 1] [1] [2] → a [1] [1] [3] → a [1] [2] [0] → a [1] [2] [1] → a [1] [2] [ 2] → a [1] [2] [3]

Two-dimensional array reference

The elements of a two-dimensional array are represented as:

Array name [subscript] [subscript]

Such as:

 a [2] [3]

Subscripts can be integer expressions,Such as a [2-1] [2 * 2-1]. Do not write in the form a [2,3], a [2-1,2 * 2-1].

Array elements are lvalues,Can appear in expressions,Can also be assigned,E.g:

 b [1] [2]=a [2] [3]/2;

When using array elements,It should be noted that the subscript value should be within the defined array size.Common errors are:

 int a [3] [4];//define an array with 3 rows and 4 columns
  ┆
  a [3] [4]=15;//Reference a [3] [4] element

Define a as a 3 × 4 array, which can have a maximum row index value of 2 and a maximum column coordinate value of 3. You can use a [2] [3] at most, a [3] [4] exceeds the range of the array.

Please make a strict distinction between a [3] [4] used when defining arrays and a [3] [4] used when referencing elements. The former a [3] [4] is used to define the number of dimensions of the array and the size of each dimension.3 and 4 in the latter a [3] [4] are subscript values,a [3] [4] represents an element.

Two-dimensional array initialization

You can initialize a two-dimensional array in the following ways:

1) Assign initial values ​​to two-dimensional arrays on separate lines.Such as

  int a [3] [4]={{1,2,3,4}, {5,6,7,8}, {9,10,11,12}};

This method of initial value assignment is relatively intuitive,Assign the data in the first curly bracket to the element in line 1,The data in the second curly brace is assigned to the element in the second row ... that is, the initial value is assigned by the row.

2) All data can be written in a curly bracket,Assign initial values ​​to the elements in the order of the array.Such as

 int a [3] [4]={1,2,3,4,5,6,7,8,9,10,11,12};

The effect is the same as before.But the first method is better,Line by line,The boundaries are clear.If there is more data in the second method,Written into a large piece,Easy to miss,Not easy to check.

3) Initial values ​​can be assigned to some elements.Such as:

 int a [3] [4]={{1}, {5}, {9}};

Its role is to assign initial values ​​only to the elements in the first column of each row.The remaining element values ​​are automatically set to 0. Each element of the array after initial value assignment is:

1 0 0 0
5 0 0 0
9 0 0 0

You can also assign an initial value to an element in each row:

 int a [3] [4]={{1}, {0,6}, {0,0,11}};

The array elements after initialization are as follows:

1 0 0 0
0 6 0 0
0 0 11 0

This method is more convenient for non-zero elements,You don't have to write all 0s,Just enter a small amount of data.You can also assign initial values ​​to only a few rows of elements:

 int a [3] [4]={{1}, {5,6}};

The array elements are:

1 0 0 0
5 6 0 0
0 0 0 0

Line 3 is not assigned an initial value.You can also assign no initial value to the second line:

 int a [3] [4]={{1}, {}, {9}};

4) If all elements are assigned initial values ​​(that is, all initial data is provided), the length of the first dimension may not be specified when defining the array.But the length of the second dimension cannot be saved.Such as:

 int a [3] [4]={1,2,3,4,5,6,7,8,9,10,11,12};

Can be written as

 int a [] [4]={1,2,3,4,5,6,7,8,9,10,11,12};

The system allocates storage space based on the total number of data.There are 12 data in total, 4 columns per row, of course, it can be determined as 3 rows.

In the definition, you can also assign initial values ​​to some elements and omit the length of the first dimension.However, initial values ​​should be assigned to branches.Such as

 int a [] [4]={{0,0,3}, {}, {0,10}};

This way of writing,Can inform the compilation system:There are 3 rows in the array. The elements of the array are:

0 0 3 0
0 0 0 0
0 10 0 0

C++ uses the square brackets a [] [] when defining arrays and representing array elements.Useful when initializing an array,It makes the concept clear,Easy to use,Not prone to errors.

Example of a two-dimensional array program

[Example] Swap the elements of a two-dimensional array with rows and columns.Save to another two-dimensional array.E.g:

The procedure is as follows:

#include<iostream>
using namespace std;
int main ()
{
  int a [2] [3]={{1,2,3}, {4,5,6}};
  int b [3] [2], i, j;
  cout<"array a:"<endl;
  for (i=0;i<= 1;i ++)
  {
   for (j=0;j<= 2;j ++)
   {
     cout<a [i] [j]<<""
     b [j] [i]=a [i] [j];
   }
   cout<endl;
  }
  cout<"array b:"<endl;
  for (i=0;i<= 2;i ++)
  {
   for (j=0;j<= 1;j ++)
     cout<b [i] [j]<<""
   cout<endl;
  }
  return 0;
}

The results are as follows:

array a:
 1 2 3
 4 5 6
array b:
 1 4
 2 5
 3 6

[Example] There is a 3 × 4 matrix, and the program is required to find the value of the element with the largest value.As well as the line and column numbers it is in.

Initially assign the value of a [0] [0] to the variable max, and then compare the next element to it,The larger of the two median values ​​is stored in max, and then the next element is compared with the new max until the last element is compared.The final value of max is the maximum value among all the elements of the array.The procedure is as follows:

#include<iostream>
using namespace std;
int main ()
{
  int i, j, row=0, colum=0, max;
  int a [3] [4]={{5,12,23,56}, {19,28,37,46}, {-12, -34,6,8}};
  max=a [0] [0];//to take the value of a [0] [0] when max starts
  for (i=0;i<= 2;i ++) //From line 0 to line 2
   for (j=0;j<= 3;j ++) //From column 0 to column 3
     if (a [i] [j]>max) //If an element is greater than max
     {
      max=a [i] [j];//max will take the value of this element
      row=i;//Note the row number of the element i
      colum=j;//Note down the column number of the element j
     }
  cout<<"max="<<max<" ;, row ="<&row;<", column =<<colum<endl;
  return 0;
}

The output is

max=56, row=0, column=3
c
  • Previous In-depth analysis of character arrays and methods of handling strings in C ++
  • Next C # method to implement program waiting for delayed execution