c语言数组学习
The array is the most common data structure in computer science because it is part of every programming language, even though in some languages it may be called something else, such as a list. In this article I’m going to discuss how to create and use arrays in C++. I am going to limit my discussion to single dimension arrays and I will cover multi-dimensional arrays in a future article.
数组是计算机科学中最常见的数据结构,因为它是每种编程语言的一部分,即使在某些语言中它也可以称为其他名称,例如列表。 在本文中,我将讨论如何在C ++中创建和使用数组。 我将把讨论仅限于一维数组,在以后的文章中我将介绍多维数组。
定义的数组 (Arrays Defined)
An array is a set of contiguous memory addresses that are reserved to store data of a specific data type. An array must be declared with a name, a data type, and a size, meaning the number of data elements to store in the array.
数组是一组连续的内存地址,这些地址保留用于存储特定数据类型的数据。 必须使用名称,数据类型和大小声明数组,这意味着要存储在数组中的数据元素的数量。
Array sizes are fixed in C++, which can create problems when a program needs more storage space than was originally allocated.
数组大小在C ++中是固定的,当程序需要的存储空间比最初分配的存储空间更多时,这会造成问题。
Array elements are accessed via the element’s index position in the array. Array elements are ordered starting at position 0 and the last element is stored at the index position that is 1 less than the number of elements in the array.
数组元素是通过元素在数组中的索引位置访问的。 数组元素从位置0开始进行排序,最后一个元素存储在比数组中元素数量少1的索引位置。
声明数组 (Declaring Arrays)
As I mentioned above, an array is declared with a data type, a name, and a size. It is common to specify a constant for the size of the array because any program using an array will need to reference the size of the array many times.
如前所述,数组是用数据类型,名称和大小声明的。 通常为数组的大小指定一个常数,因为使用数组的任何程序都需要多次引用数组的大小。
You can declare an array without specifying the data to be stored in the array or you can provide an initializer list with data for the array.
您可以在不指定要存储在数组中的数据的情况下声明一个数组,也可以为初始化器列表提供该数组的数据。
Here is the syntax template for the first type of array declaration:
这是数组声明的第一种类型的语法模板:
data-type array-name[number-of-elements];
数据类型数组名称[元素数];
Here is the syntax template for the second type of array declaration:
这是第二种数组声明的语法模板:
data-type array-name[(number-of-elements)] = {comma-separated-list-of-data};
数据类型数组名称[(元素数)] = {数据的逗号分隔列表};
The specification for the number of elements is in parentheses because you can leave this out when providing an initializer list and the compiler will determine the size of the array by counting the number of elements in the list.
元素数量的规范在括号中,因为您可以在提供初始化列表时忽略此内容,并且编译器将通过计算列表中元素的数量来确定数组的大小。
Here are some examples of the first form of array declaration:
这是数组声明的第一种形式的一些示例:
const int numElements = 10;
int grades[numElements];
string names[numElements];
bool flags[numElements];
char letters[numElements];
Now let’s look at some declarations that use an initializer list:
现在,让我们看一些使用初始化列表的声明:
const int numElements = 5;
int numbers[numElements] = {1,2,3,4,5};
const int numNames = 3;
string names[] = {"Cynthia", "Jonathan", "Raymone"};
cont int numFlags = 4;
bool flags[] = {false, true, true, false};
I wrote a couple declarations putting the number of elements in brackets and letting the compiler determine the number of elements. However, even if you choose to let the compiler determine the number of elements in the array, you should still declare a constant with the number of elements in the array.
我写了一些声明,将元素数放在方括号中,让编译器确定元素数。 但是,即使您选择让编译器确定数组中元素的数量,您仍应使用数组中元素的数量声明一个常量。
访问数组 (Accessing Arrays)
The elements of an array are accessed by specifying the index position of the element you want using the []
operator. For example, here are some statements that assign some data into an array:
通过使用[]
运算符指定所需元素的索引位置,可以访问数组的元素。 例如,以下是一些将一些数据分配到数组中的语句:
numbers[0] = 101;
numbers[1] = 103;
numbers[2] = 105;
Stored data is accessed from an array also using the []
operator. For example:
也可以使用[]
运算符从数组访问存储的数据。 例如:
int subtotal = numbers[0] + numbers[1] + numbers[2];
Here is another example of array access, this time using a for
loop to initialize an array with a set of numbers:
这是数组访问的另一个示例,这次使用for
循环初始化具有一组数字的数组:
#include <iostream>
using namespace std;int main()
{
const int numElements = 5;
int numbers[numElements];
for (int i = 0; i < numElements; i++) {
numbers[i] = i + 1;
}
return 0;
}
Here is another example using a for
loop, this time access the array as part of the process of computing an average:
这是使用for
循环的另一个示例,这次作为计算平均值过程的一部分访问数组:
int main()
{
const int numElements = 5;
int grades[numElements] = {81, 78, 91, 77, 66};
int total = 0;
for (int i = 0; i < numElements; i++) {
total += grades[i];
}
double average = static_cast<double>(total) / numElements;
cout << "The average grade is: " << average << endl;
return 0;
}
Here is the output from this program:
这是该程序的输出:
The average grade is: 78.6
Because this is an introductory article, I used int
to initialize the for loop control variable. If this were a more advanced article, I would have used size_t
instead.
因为这是一篇介绍性文章,所以我使用int
初始化了for循环控制变量。 如果这是更高级的文章,我会改用size_t
。
I should also mention that the best way to traverse an array from start to end when you want to access every element is to use a range for
loop. Here is the program rewritten with that in mind:
我还要提到的是最好的办法,从开始的时候,你要访问的每一个元素是使用范围遍历数组结束for
循环。 这是考虑到这一点而改写的程序:
int main()
{
const int numElements = 5;
int grades[numElements] = {81, 78, 91, 77, 66};
int total = 0;
for (auto grade : grades) {
total += grade;
}
double average = static_cast<double>(total) / numElements;
cout << "The average grade is: " << average << endl;
return 0;
}
数组作为函数参数 (Arrays as Function Arguments)
I’ve made a point of emphasizing that you should always declare a constant that holds the number of elements in an array. The first reason you need to do this is so that when you write an index for
loop to traverse an array, you will have a constant available to let the loop know when to stop.
我要强调的是,您应该始终声明一个常数,该常数可以容纳数组中元素的数量。 您需要执行此操作的第一个原因是,当您for
循环编写索引以遍历数组时,将具有一个常量,可让循环知道何时停止。
This is important because C++ arrays do not have bounds checking, which means that you can accidentally access memory outside an array without triggering an error. As someone maybe famous once said, “C++ gives you just enough rope to hang yourself.” Newer language will throw an exception when this happens but C++ just assumes that’s what you meant to do.
这很重要,因为C ++数组没有边界检查,这意味着您可以意外访问数组外部的内存而不会触发错误。 正如有人可能曾经说过的那样:“ C ++给您足够的绳索来吊死自己。” 发生这种情况时,较新的语言将引发异常,但是C ++只是假设这就是您的意图。
Another reason to have a constant hold the number of array elements is for when you want to pass the array to a function. You can’t use a range for
loop to access array elements from within a function body so you must use an index for
loop. This means you need to know when to stop the loop and the constant parameter provides that value.
保持数组元素数量不变的另一个原因是当您要将数组传递给函数时。 你不能使用范围for
循环访问数组元素从一个函数体内,所以你必须使用一个索引for
循环。 这意味着您需要知道何时停止循环,并且常量参数会提供该值。
Knowing this, I can show you how to pass an array to a function. I’ll rewrite the grade averaging program from above with a function that computes the average:
知道了这一点,我可以向您展示如何将数组传递给函数。 我将使用计算平均值的函数从上面重写平均成绩程序:
double gradeAvg(int arr[], int arraySz) {
int total = 0;
for (int i = 0; i < arraySz; i++) {
total += arr[i];
}
double average = static_cast<double>(total) / arraySz;
return average;
}int main()
{
const int numElements = 5;
int grades[numElements] = {81, 78, 91, 77, 66};
int total = 0;
double average = gradeAvg(grades, numElements);
cout << "The average grade is: " << average << endl;
return 0;
}
The output from this program is:
该程序的输出为:
The average grade is: 78.6
Arrays can also be returned from a function but that requires pointers so I’ll have to save that discussion to another day.
数组也可以从函数中返回,但是它需要指针,因此我不得不将讨论保留到另一天。
数组很棒,但矢量可能更好 (Arrays are Great but Vectors May be Better)
While I’ve devoted this article to explaining how to use arrays, most C++ programmers are now using vectors as the first data structure of choice for storing sequential data. There are several reasons for this, including the fact that the vector class implementation in the Standard Template Library is very efficient now, and, probably most importantly, vectors can grow and shrink as needed. In my next article I’ll discuss how to use vectors in C++ and you will see the advantages they have over arrays.
尽管我专门介绍了如何使用数组,但是大多数C ++程序员现在都将向量用作存储顺序数据的首选首选数据结构。 造成这种情况的原因有很多,其中包括标准模板库中的矢量类实现现在非常高效的事实,而且最重要的是,矢量可以根据需要进行增长和收缩。 在我的下一篇文章中,我将讨论如何在C ++中使用向量,您将看到它们比数组具有的优势。
Thanks for reading and please email me with comments and suggestions. If you are interested in my online computer programming courses, please visit https://learningcpp.teachable.com.
感谢您的阅读,请给我发送评论和建议。 如果您对我的在线计算机编程课程感兴趣,请访问https://learningcpp.teachable.com 。
翻译自: https://levelup.gitconnected.com/learning-c-using-arrays-2b7d95cd2a29
c语言数组学习