1. Array in CPP
C + + supports array data structures, which can store an ordered collection of elements of the same type with a fixed size. Array is used to store a series of data, but it is often regarded as a series of variables of the same type.
The declaration of an array is not to declare individual variables, such as a0,a1,a2,a3,a4...,a99, but to declare an array variable, such as as as, and then use as[0],as[1],as[2],...,as[99]
Represents a single variable, and the specific elements of the array can be accessed by index. All arrays are composed of continuous memory locations. The lowest address corresponds to the first element and the highest address corresponds to the last element.
2. Declaration array
When declaring an array in C + +, you need to specify the type and number of elements, as shown below:
Data type array name [number of elements];
The format declared above is the declaration of one-dimensional array, in which the number of elements must be an integer constant greater than 0, and the data type can be any valid C + + data type. For example, declare a double containing 10
Array balance of elements. The declaration statement is:
double balance[10];
3. Initialize array
In C + +, you can initialize arrays one by one or use an initialization statement, as shown below:
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces {} cannot be greater than the number of elements specified in square brackets [] when the array is declared.
If the size of the array is omitted, the size of the array is the number of elements at initialization. Therefore, if it is in the following format, an array will be created, which is exactly the same as the array created in the previous instance
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The following statement assigns the value of the fifth element in the array to 666.6. All arrays take 0 as the index of their first element, also known as the base index,
The last index of the array is the total size of the array minus 1.
balance[4] = 666.6;
4. Access array elements
Array elements can be accessed by adding an index to the array name. The index of the element is placed in square brackets, following the array name. For example:
double salary = balance[3];
Examples of declaring array, initializing array and accessing array elements are as follows:
#include "iostream" #include "iomanip" using namespace std; using std::setw; // setw() function to format the output int main(){ int a[10]; // Declare an integer array containing 10 elements // Initialize array for (int i = 0; i < 10; i++) a[i] = i + 100; cout << "Element index" << setw(13) << "Element value" << endl; // Output each element in the array for (int j = 0; j < 10; j++) cout << setw(7) << j << setw(13) << a[j] << endl; return 0; }
5. Concepts related to arrays
5.1 multidimensional array
C + + supports multidimensional arrays. The general form of multidimensional array declaration is as follows:
Data type name array name [size1][size2]...[sizeN];
For example, the following declaration creates a three-dimensional integer array:
int tridim[5][10][4];
Two dimensional array
The simplest form of multidimensional array is two-dimensional array. A two-dimensional array, in essence, is a list of one-dimensional arrays. Declare a two-dimensional integer array of x rows and y columns, as follows:
Data type array name [x][y];
A two-dimensional array can be considered a table with x rows and y columns. The following is a two-dimensional array with 3 rows and 4 columns:
Therefore, each element in the array is identified by the element name in the form of a[i][j], where a is the array name and I and j are the subscripts that uniquely identify each element in a.
Initialize 2D array
Multidimensional arrays can be initialized by specifying values for each row in parentheses. Below is an array with 3 rows and 4 columns.
int a[3][4] = { {0, 1, 2, 3}, /* Initializes the row with index number 0 */ {4, 5, 6, 7}, /* Initializes a row with index number 1 */ {8, 9, 10, 11}, /* Initializes the row with index number 2 */ };
Internally nested parentheses are optional. The following initialization is the same as the above:
int a[3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
Accessing 2D array elements
The elements in a two-dimensional array are accessed by using subscripts, that is, the row index and column index of the array. For example:
int val = a[2][3];
The two-dimensional array is as follows:
//1. Two dimensional array int aa[5][2] = {{0, 0}, {1, 2}, {2, 4}, {5, 7}, {9, 10}}; for (int i = 0; i < 5; i++){ for (int j = 0; j < 2; j++) { cout << "aa[" << i << "][" << j << "] = " << aa[i][j] << endl; } }
5.2 pointer to array -- array pointer
The array name is a constant pointer (int const *p;) to the first element in the array. Therefore, double a[40];a is a pointer to & A [0], that is, the address of the first element of array a. So,
The following program fragment p is assigned to the address of the first element of a:
double *p;
double a[10];
p = a;
It is legal to use array names as constant pointers, so * (a+4) is a legal way to access a[4] data. Once the address of the first element is stored in p, you can use * p,*(p+1),*(p+2), etc
To access the elements of the array.
//2. Pointer to array: array pointer
double b[5] = {12.4, 3.1, 5.6, 0.8, 5.4}; double *p; // A pointer to double type can store the address of a variable of double type p=b; cout << "Use array values of pointers "<<endl; for(inti=0;i<5;i++) cout << "*(p + " << i << ") = " << *(p + i) << endl; cout << "use b Array value as address " << endl; for(inti=0;i<5;i++) cout << "*(b + " << i << ") = " << *(b + i) << endl;
In C + +, pass char * or char [] to cout for output, and the result will be the whole string. If you want to obtain the address of the string (the address of the first character), you can use the following method:
Forced conversion to other pointers (non char), which can be void*, float*,int*,double *, etc. The address of s[0] cannot be output with & s[0], because & s[0] will return char *,
For char*,cout processes it as a string, looks down the character and outputs it until the end of the character *.
//In C + +, pass char * or char [] to cout for output, and the result will be the whole string. If you want to get the address of the string, force conversion to another pointer (not char *)
char var[MAX] = {'a', 'b', 'c'}; char*ptr; ptr=var; for (int i = 0; i < 3; i++){ cout << "var[" << i << "]Your address is = " << (int *)ptr << endl; cout << "var[" << i << "] = " << *ptr << endl; ptr++; // Move to next position }
5.3 passing arrays to functions in C + +
In C + +, you can pass a pointer to an array by specifying an array name without an index
When C + + passes an array to a function, the array type is automatically converted to a pointer type, so the actual address is passed
If you want to pass a one-dimensional array as a parameter in a function, you must declare the function formal parameters in the following three ways. The results of these three declaration methods are the same, because each method will tell the compiler that it will receive an integer pointer. Similarly, you can pass a multidimensional array as a formal parameter.
Mode 1(The formal parameter is a pointer)) void func1(int *param){ ... } Mode 2(The formal parameter is an array of defined sizes)) void func1(int params[10]){ ... } Mode 3(The formal parameter is an array of undefined sizes) void func1(int params[]){ ... }
Examples are as follows:
// 3. Pass array to function in C + + (method 1) int bb[5] = {1000, 2, 3, 17, 50}; double avg, avg1; // Pass a pointer to an array as an argument avg = getAverage(bb, 5); cout << "average value: " << avg << endl; /*-----------------------Method 2-----------------------*/ int bbb[5] = {1000, 2, 3, 17, 50}; int *ptr1 = bbb; // Calculate the number of array elements and the number of bytes of the integer pointer respectively size_t bbb_size = sizeof(bbb) / sizeof(int); size_t ptr1_size = sizeof(ptr1); cout << "bbb size = " << bbb_size << endl; cout << "ptr1 size = " << ptr1_size << endl; avg1 = getAverage1(bbb, 5); cout << "average value: " << avg1 << endl; // Method 1 (in the following example, the array is used as a parameter and another parameter is passed) double getAverage(int arr[], int size){ int i, sum = 0; double avg; cout << "sizeof(arr) = " << sizeof(arr) << endl; for (i = 0; i < size; i++) sum += arr[i]; avg = double(sum) / size; return avg; } // Method 2 double getAverage1(int *arr, int size){ int i, sum = 0; double avg; cout << "sizeof(arr) = " << sizeof(arr) << endl; for (i = 0; i < size; i++) sum += arr[i]; avg = double(sum) / size; return avg; }
5.4 return array from function
C + + does not allow returning a complete array as a function parameter. However, you can return a pointer to an array by specifying an array name without an index. C + + does not support returning the address of a local variable outside a function unless the local variable is defined as a static variable. If you want to return a one-dimensional array from a function, you must declare a function that returns a pointer (pointer function), as follows:
int * func(){ ... }
Examples are as follows:
// Functions to generate and return random numbers int * getRandom() { static int r[10]; // C + + does not support returning the address of a local variable outside a function unless the local variable is defined as a static variable // Set random number seed srand((unsigned)time(NULL)); for (int i = 0; i < 10; i++){ r[i] = rand(); cout << "r[" << i << "] = " << r[i] << endl; } return r; } // 4. Return array from function -- pointer function int *p1; p1 = getRandom(); for (int i = 0; i < 10; i++) cout << "*( p1 + " << i << ") = " << *(p1 + i) << endl;
6. Detail knowledge in the array
It is special to directly initialize the character array char. This initialization requires a null ending. As follows:
char a1[] = {'p', 'y', 't', 'h', 'o', 'n'}; // Initialization, no null char a2[] = {'p', 'y', 't', 'h', 'o', 'n', '\0'}; // Initialization, explicitly null char a3[] = "python"; // null terminator automatically added const char a4[6] = "python"; // An error is reported. There is no null location
The size of the array is fixed and no additional elements can be added. When you want to define characters of non fixed size, use vector!
vector<int> vec; // Create vectors to store integer data int m; // Show vec initial size cout << "vector size = " << vec.size() << endl; // Append 5 integer values to vector vec for(int m = 0; m < 5; m++) vec.push_back(m); // Displays the size of the appended vec cout << "Additional vector size = " << vec.size() << endl;
In C + +, setw(int n) is used to control the output interval (n-1 spaces). The default content filled in by setw() is spaces. You can use setfill() in combination with other characters to fill.
cout << setfill('*') << setw(5) << 'a' << endl;
Static and dynamic arrays:
static state int array[100]; Array defined array,The array was not initialized int array[100] = {1, 2}; Array defined and initialized array dynamic int * array = new int[100]; An array of length 100 was allocated array delete [] array; dynamic int * array = new int[100]{1, 2}; Is an array of length 100 array Initialize the first two elements delete [] array;
Aggregation methods can be used for array initialization, but not for assignment. Examples are as follows:
int array[] = {5,10,20,40}; // legitimate int array[]; int main() { array[] = {5,10,20,40}; // wrongful return 0; }
An array can be an expression containing variables when used, but a constant expression must be used when declaring an array. For example:
// legitimate const int a=19; long b[a]; // legitimate const int a=19; long b[a+5]; // wrongful int a=19; long b[a+5];
Declare an array of arbitrary length, which can be explicitly typed, for example:
int a=19; int b[(const int)a];
You can also define a constant to declare, for example:
int a=19; const int a1=a; int b[a1];
Vector: a data structure in C + +, specifically a class. It is equivalent to a dynamic array. When programmers can't know the size of the array they need, using it to solve the problem can achieve the purpose of maximum space saving.
Usage:
1. The document includes:
First, add #include < vector > at the beginning of the program to include the required class file vector; And be sure to add
using namespace std;
2. Variable declaration:
2.1 example: declare an int vector to replace a one-dimensional array: vector < int > A; (equal to declaring an int array a [], the size is not specified,
It can be dynamically added and deleted).
2.2 example: use vector instead of two-dimensional array. In fact, just declare a one-dimensional array vector, and the name of an array actually represents its first address,
So just declare a vector of an address, that is: vector < int * > a. It is the same as replacing 3D array with ideal vector, vector < int * * > A;
3. Specific usage and function call:
3.1 the elements in the vector are the same as the array, for example:
vector <int *> a int b = 5; a.push_back(b);//This function is explained in detail below cout << a[0]; //The output is 5
Assign a value to a vector using an array:
vector<int> v( a, a+sizeof(a)/sizeof(a[0]) );
Or:
int a[]={1,2,3,4,5,6,7,8,9}; typedef vector<int> vec_int; vec_int vecArray(a,a+9);
Original text: https://www.jianshu.com/p/0d3ffd335e24