設為首頁收藏本站

艾歐踢論壇

 找回密碼
 立即註冊

QQ登錄

只需一步,快速開始

搜索
熱搜: 活動 交友 discuz
查看: 717|回復: 0
打印 上一主題 下一主題

9. Arrays

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2016-1-1 18:46:51 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
9.  Arrays
9.1  Array Declaration and Usage
Suppose that you want to find the average of the marks for a class of 30 students, you certainly do not want to create 30 variables: mark1, mark2, ..., mark30. Instead, You could use a single variable, called an array, with 30 elements.
An array is a list of elements of the same type, identified by a pair of square brackets [ ].
To use an array, you need to declare the array with 3 things: a name, a type and a dimension (or size, or length).
The syntax is:
type arrayName[arraylength];  // arraylength can be a literal or a variable
I recommend using a plural name for array, e.g., marks, rows, numbers. For example,
int marks[5];        // Declare an int array called marks with 5 elements
double numbers[10];  // Declare an double array of 10 elements
const int SIZE = 9;
float temps[SIZE];   // Use const int as array length

// Some compilers support an variable as array length, e.g.,
int size;
cout << "Enter the length of the array: ";
cin >> size;
float values[size];
Take note that, in C++, the value of the elements are undefined after declaration.
You can also initialize the array during declaration with a comma-separated list of values, as follows:
// Declare and initialize an int array of 3 elements
int numbers[3] = {11, 33, 44};
// If length is omitted, the compiler counts the elements
int numbers[] = {11, 33, 44};
  // Number of elements in the initialization shall be equal to or less than length
int numbers[5] = {11, 33, 44};
  // Remaining elements are zero. Confusing! Don't do this
int numbers[2] = {11, 33, 44};
  // ERROR: too many initializers
  // Use {0} or {} to initialize all elements to 0
int numbers[5] = {0};
// First element to 0, the rest also to zero
int numbers[5] = {};
// All element to 0 too


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* Test local array initialization (TestArrayInit.cpp) */
#include <iostream>
using namespace std;

int main() {
   int const SIZE = 5;

   int a1[SIZE];   // Uninitialized
   for (int i = 0; i < SIZE; ++i) cout << a1 << " ";
   cout << endl;   // ? ? ? ? ?

   int a2[SIZE] = {21, 22, 23, 24, 25}; // All elements initialized
  for (int i = 0; i < SIZE; ++i) cout << a2 << " ";
  cout << endl;   // 21 22 23 24 25

   int a3[] = {31, 32, 33, 34, 35};   // Size deduced from init values
   int a3Size = sizeof(a3)/sizeof(int);
   cout << "Size is " << a3Size << endl;   // 5
   for (int i = 0; i < a3Size; ++i) cout << a3 << " ";
   cout << endl;   // 31 32 33 34 35

   int a4[SIZE] = {41, 42};  // Leading elements initialized, the rests to 0
   for (int i = 0; i < SIZE; ++i) cout << a4 << " ";
   cout << endl;   // 41 42 0 0 0

   int a5[SIZE] = {0};  // First elements to 0, the rests to 0 too
   for (int i = 0; i < SIZE; ++i) cout << a5 << " ";
   cout << endl;   // 0 0 0 0 0

   int a6[SIZE] = {};   // All elements to 0 too
   for (int i = 0; i < SIZE; ++i) cout << a6 << " ";
   cout << endl;   // 0 0 0 0 0
}
You can refer to an element of an array via an index (or subscript) enclosed within the square bracket [ ].  C++'s array index begins with zero. For example, suppose that marks is an int array of 5 elements, then the 5 elements are: marks[0], marks[1], marks[2], marks[3], and marks[4].
// Declare & allocate a 5-element int array
int marks[5];
// Assign values to the elements
marks[0] = 95;
marks[1] = 85;
marks[2] = 77;
marks[3] = 69;
marks[4] = 66;
cout << marks[0] << endl;
cout << marks[3] + marks[4] << endl;


To create an array, you need to known the length (or size) of the array in advance, and allocate accordingly.  Once an array is created, its length is fixed and cannot be changed. At times, it is hard to ascertain the length of an array (e.g., how many students in a class?). Nonetheless, you need to estimate the length and allocate an upper bound. This  is probably the major drawback of using an array. C++ has a vector template class (and C++11 added an array template class), which supports dynamic resizable array.
You can find the array length using expression sizeof(arrayName)/sizeof(arrayName[0]), where sizeof(arrayName) returns the total bytes of the array and sizeof(arrayName[0]) returns the bytes of first element.
C/C++ does not perform array index-bound check.  In other words, if the index is beyond the array's bounds, it does not issue a warning/error. For example,
const int size = 5;
int numbers[size];  // array index from 0 to 4
// Index out of bound!
// Can compiled and run, but could pose very serious side effect!
numbers[88] = 999;
cout << numbers[77] << endl;
This is another pitfall of C/C++.
Checking the index bound consumes computation power and depicts the performance.
However, it is better to be safe than fast. Newer programming languages such as Java/C# performs array index bound check.
9.2  Array and Loop
Arrays works hand-in-hand with loops. You can process all the elements of an array via a loop, for example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
*  Find the mean and standard deviation of numbers kept in an array (MeanStdArray.cpp).
*/
#include <iostream>
#include <iomanip>
#include <cmath>
#define SIZE 7
using namespace std;

int main() {
   int marks[] = {74, 43, 58, 60, 90, 64, 70};
   int sum = 0;
   int sumSq = 0;
   double mean, stdDev;
   for (int i = 0; i < SIZE; ++i) {
      sum += marks;
      sumSq += marks*marks;
    }
   mean = (double)sum/SIZE;
   cout << fixed << "Mean is " << setprecision(2) << mean << endl;

   stdDev = sqrt((double)sumSq/SIZE - mean*mean);
   cout << fixed << "Std dev is " << setprecision(2) << stdDev << endl;

  return 0;
}
Exercises[TODO]
9.3  Range-based for loop (C++11)
C++11 introduces a range-based for loop (or for-each loop) to iterate thru an array, as illustrated in the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* Testing For-each loop (TestForEach.cpp) */
#include <iostream>
using namespace std;

int main() {
   int numbers[] = {11, 22, 33, 44, 55};

   // For each member called number of array numbers - read only
    for (int number : numbers) {
      cout << number << endl;
   }

    // To modify members, need to use reference (&)
   for (int &number : numbers) {
      number = 99;
   }

    for (int number : numbers) {
      cout << number << endl;
   }
   return 0;
}
To compile the program under GNU GCC (g++), you may need to specify option -std=c++0x or -std=c++11:
g++ -std=c++0x -o TestForEach.exe TestForEach.cpp
// or
g++ -std=c++11 -o TestForEach.exe TestForEach.cpp
9.4  Multi-Dimensional Array
For example,
int[2][3] = { {11, 22, 33}, {44, 55, 66} };


For 2D array (table), the first index is the row number, second index is the column number.
The elements are stored in a so-called row-major manner, where the column index runs out first.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* Test Multi-dimensional Array (Test2DArray.cpp) */
#include <iostream>
using namespace std;
void printArray(const int[][3], int);

int main() {
   int myArray[][3] = {{8, 2, 4}, {7, 5, 2}}; // 2x3 initialized
                 // Only the first index can be omitted and implied
   printArray(myArray, 2);
   return 0;
}

// Print the contents of rows-by-3 array (columns is fixed)
void printArray(const int array[][3], int rows) {
   for (int i = 0; i < rows; ++i) {
      for (int j = 0; j < 3; ++j) {
         cout << array[j] << " ";
    }
    cout << endl;
   }
}
9.5  Array of Characters - C-String
In C, a string is a char array terminated by a NULL character '\0' (ASCII code of Hex 0).
C++ provides a new string class under header <string>.
The original string in C is known as C-String (or C-style String or Character String). You could allocate a C-string via:
char message[256];     // Declare a char array
                        // Can hold a C-String of up to 255 characters terminated by '\0'
char str1[] = "Hello"; // Declare and initialize with a "string literal".
                       // The length of array is number of characters + 1 (for '\0').
char str1char[] = {'H', 'e', 'l', 'l', 'o', '\0'};  // Same as above
char str2[256] = "Hello";  // Length of array is 256, keeping a smaller string.
For novices, avoid C-string. Use C++ string (in header <string>) discussed earlier.
Example
You can use cin and cout to handle C-strings.

  • cin << reads a string delimited by whitespace;
  • cin.getline(var, size) reads a string of into var till newline of length up to size-1, discarding the newline (replaced by '\0'). The size typically corresponds to the length of the C-string array.
  • cin.get(var, size) reads a string till newline, but leaves the newline in the input buffer.
  • cin.get(), without argument, reads the next character.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* Test C-string (TestCString.cpp) */
#include <iostream>
using namespace std;

int main() {
   char msg[256]; // Hold a string of up to 255 characters (terminated by '\0')

   cout << "Enter a message (with space)" << endl;
   cin.getline(msg, 256);  // Read up to 255 characters into msg
   cout << msg << endl;

  // Access via null-terminated character array
   for (int i = 0; msg != '\0'; ++i) {
      cout << msg;
   }
  cout << endl;

  cout << "Enter a word (without space)" << endl;
  cin >> msg;
  cout << msg << endl;

  // Access via null-terminated character array
   for (int i = 0; msg != '\0'; ++i) {
    cout << msg;
  }
   cout << endl;
   return 0;
}
9.6  Exercises
[TODO]

分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 轉播轉播 分享分享 分享淘帖
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|Archiver|手機版|艾歐踢創新工坊    

GMT+8, 2024-6-13 03:09 , Processed in 0.267787 second(s), 21 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表