search
HomeBackend DevelopmentC#.Net TutorialHow to initialize a c++ array

How to initialize a c++ array

Oct 15, 2021 pm 02:09 PM
arrayc++

c Method to initialize an array: 1. Define the array first and then assign a value to the array. The syntax is "data type array name [length]; array name [subscript] = value;"; 2. Initialize the array when defining the array. , syntax "data type array name [length] = [value list]".

How to initialize a c++ array

The operating environment of this tutorial: Windows 7 system, C 17 version, Dell G3 computer.

Sometimes it is more appropriate to set the variable value in the program than to enter the variable value. However, writing separate assignment statements for each element of the array can mean a lot of typing, especially for large arrays.

For example, consider a program:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    const int NUM_MONTHS = 12;
    int days[NUM_MONTHS];
    days[0] = 31; // January
    days[1] = 28; // February
    days[2] = 31; // March
    days[3] = 30; // April
    days[4] = 31; // May
    days[5] = 30; // June
    days[6] = 31; // July
    days[7] = 31; // August
    days[8] = 30; // September
    days[9] = 31; // October
    days[10] = 30; // November
    days[11] = 31; // December
    for (int month = 0; month < NUM_MONTHS; month++)
    {
        cout << "Month "<< setw (2) << (month+1) << " has ";
        cout << days[month] << " days.\n";
    }
    return 0;
}

Program output:

Month  1 has 31 days.
Month  2 has 28 days.
Month  3 has 31 days.
Month  4 has 30 days.
Month  5 has 31 days.
Month  6 has 30 days.
Month  7 has 31 days.
Month  8 has 31 days.
Month  9 has 30 days.
Month 10 has 31 days.
Month 11 has 30 days.
Month 12 has 31 days.

Fortunately, there is an option. C allows initializing arrays when they are defined. By using an initializer list, you can easily initialize all elements of an array when you create it. The following statement defines the days array and initializes it with the same values ​​established by the set of assignment statements in the previous program:

int days [NUM_MONTHS] = {31,28,31,30,31,30,31,31,30,31,30, 31};

The values ​​are stored in the array elements in the order in which they appear in the list (the first The value 31 is stored in days[0], the second value 28 is stored in days[1], etc.). The following figure shows the contents of the array after initialization.

How to initialize a c++ array

The following program is a modified version of the above program. It initializes the days array when it is created, rather than using a separate assignment statement. Note that the initialization list is spread across multiple lines. The program also adds an array of string objects to hold the month names:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
    const int NUM_MONTHS = 12;
    string name[NUM_MONTHS]={ "January", "February", "March", "April", "May" , "June", "July", "August", "September", "october", "November", "December"};
    int days[NUM_MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    for (int month = 0; month < NUM_MONTHS; month++)
    {
        cout << setw(9) << left << name[month] << " has ";
        cout << days [month] << " days. \n";
    }
    return 0;
}

Program output:

January   has 31 days.
February  has 28 days.
March     has 31 days.
April     has 30 days.
May       has 31 days.
June      has 30 days.
July      has 31 days.
August    has 31 days.
September has 30 days.
october   has 31 days.
November  has 30 days.
December  has 31 days.

So far, it has been demonstrated how to fill the array with numerical values ​​and then display all the values . However, sometimes more functionality may be needed, such as retrieving a specific value from an array. The following program is a variation of the above program that displays the number of days in a month selected by the user.

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
    const int NUM_MONTHS = 12;
    int choice;
    string name[NUM_MONTHS]={ "January", "February", "March", "April", "May" , "June", "July", "August", "September", "october", "November", "December"};
    int days[NUM_MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    cout << "This program will tell you how many days are "<< "in any month.\n\n";
    // Display the months
    for (int month = 1; month <= NUM_MONTHS; month++)
        cout << setw (2) << month << " " << name [month-1] << endl;
    cout << "\nEnter the number of the month you want: ";
    cin >> choice;
    // Use the choice the user entered to get the name of
    // the month and its number of days from the arrays.
    cout << "The month of " << name [choice-1] << " has " << days[choice-1] << " days.\n";
    return 0;
}

The program output is:

This program will tell you how many days are in any month.

1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 october
11 November
12 December

Enter the number of the month you want: 4
The month of April has 30 days.

Start from array element 1

There is a lot of logic in the real world When building a model for things starting with 1, many teachers will prefer that students not use element 0, but instead start storing actual data from element 1. The number of months in the year is a good example. In this case, you can declare the name and days arrays to have 13 elements each and initialize them as follows:

string name[NUM_MONTHS+1]={" ", "January", "February", "March", "April", "May" , "June", "July", "August", "September", "october", "November", "December"};
int days[NUM_MONTHS+1] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

Note that array element 0 is not used. It's just a virtual value. This will store the name of January in name[1], the name of February in name[2], and so on. Likewise, the number of days in January will be stored in the days[1] element, the number of days in February in the days[2] element, and so on.

If you use the above method to define and initialize the array, the loop should be rewritten in the following form. It will display the contents of array elements 1~12 instead of elements 0~11 like before.

for (int month = 1; month <= NUM_MONTHS; month++)
{
    cout << setw(9) << left << name[month] << " has ";
    cout << days[month] << " days.\n";
}

If the actual data is stored starting with element 1, then there is no need to add 1 to the array subscript to locate specific data. The following is a modification of the statement that lists the number and name of each month:

for (int month = 1; month <= NUM_MONTHS; month++)
    cout << setw (2) << month << " " << name [month] << endl;

The code that displays the number of days in the month selected by the user should be modified as follows.

cout << "The month of " << name[choice] << " has "<< days [choice] << " days . \n";

Partial initialization of array

When an array is initialized, C does not have to get the value of each element, it can also just initialize it Part of the array, as shown below:

int numbers[7] = {1, 2, 4, 8};

This definition only initializes the first 4 elements of a 7-element array, as shown below.

How to initialize a c++ array
Figure 2

It is worth mentioning that the uninitialized elements in Figure 2 will all be set to zero. This is what happens when the numeric array is partially initialized. When an array of string objects is partially initialized, the uninitialized elements will all contain empty strings, that is, strings of length 0. This is true even if the partially initialized array is defined locally. However, if a local array is completely uninitialized, its elements will contain "garbage", just like other local variables.

The following program shows the contents of the numbers array after partial initialization:

#include <iostream>
using namespace std;
int main ()
{
    const int SIZE = 7;
    int numbers[SIZE] = {1, 2, 4, 8}; // Initialize the first 4 elements
    cout << "Here are the contents of the array: \n";
    for (int index = 0; index < SIZE; index++)
    cout << numbers [index] << " ";
    cout << endl;
    return 0;
}

Program output:

Here are the contents of the array:
1 2 4 8 0 0 0

Although the value of the array initialization list can be larger than the elements of the array Fewer, but no more values ​​than array elements are allowed. The following statement is illegal because the numbers array can only contain 7 values, but the initialization list contains 8 values.

int numbers [7] = {1, 2, 4, 8, 3, 5, 7, 9};    //不合法

Also, if an element is left uninitialized, all elements after that element should be left uninitialized. C does not provide a way to skip elements in an initialization list. Here is another illegal example:

int numbers [7] = {1, , 4, , 3, 5, 7};    // 不合法

Implicit array size

可以通过提供一个包含每个元素值的初始化列表来定义一个数组而不指定它的大小。C++ 会计算初始化列表中的项目数,并为数组提供相应数量的元素。例如,以下定义创建 了一个包含5个元素的数组:

double ratings [] = {1.0,1.5,2.0,2.5,3.0};

注意,如果省略大小声明符,则必须指定一个初始化列表。否则,C++ 不知道该数组有多大。

初始化变量的新方法

到目前为止,已经介绍过的定义和初始化常规变量的方法是使用赋值语句,示例如下:

int value = 5;

但是,我们已经学习过使用函数、数组以及类,所以现在是时候来介绍另外两种在定义变量的同时即进行初始化的方法。

第一种新方法是使用函数符号初始化变量。它看起来就像是给一个函数传递参数。如果您已经掌握了类的内容,那么就会注意到,它也很像是在创建类对象时给一个构造函数传递值。以下是使用函数符号定义变量 value 并初始化其值为 5 的示例语句:

int value (5);

第二种初始化变量的新方法是 C++ 11 中新引入的,使用大括号表示法。它看起来就像是刚刚上面所看到的初始化数组的方法,但是其中有两点区别:

  • 因为常规变量只能一次保存一个值,所以通过这种方法初始化变量时,大括号中只有一个值;

  • 和数组初始化列表不一样,通过这种方法初始化变量时,在大括号前面没有赋值运算符(=)。

以下是使用大括号表示法定义变量 value 并初始化其值为5的示例语句。

int value{5}; //该语句仅在C++ 11或更高版本中合法

绝大多数程序员会继续使用赋值运算符来初始化常规变量,本书也将如此,但是,大括号表示法提供了一项优点,它会检查用来初始化变量的值,并确保匹配变量的数据类型。例如,假设 doubleVal 是一个 double 类型变量,存储在其中的值为 6.2。则使用赋值运算符时,可以编写以下两种形式的语句之一:

int valuel = 4.9;    //该语句将给valuel赋值为。4
int vaule2 = doubleVal;    // 该语句将给 value2 赋值为 6

在这两种情况下,值的小数点部分都会被先截断,然后才赋值给被定义的变量。这虽然可能会导致一些问题,但 C++ 编译器是允许的,它也会提出警告,但却仍然能生成可执行文件,并且可以运行。不过,如果在这里使用的是大括号表示法,则编译器会指出这些语句产生了一个错误,并且不会生成可执行文件。必须先修复该错误,然后重新编译项目才能运行该程序。

相关推荐:《C++视频教程

The above is the detailed content of How to initialize a c++ array. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools