简体   繁体   English

如何在C ++中制作结构类型数组

[英]How to make a struct type array in C++

I want to make a program that will store the data from the Periodic Table of Elements into an array that I can access whenever I want. 我想制作一个程序,将元素周期表中的数据存储到一个数组中,以便随时随地访问。 I want to do it by making a struct with the data for each element in it, and make an instance of that struct for each element in an array "periodicTable[119]" 我想通过为每个元素中的数据制作一个结构来实现,并为数组“ periodicTable [119]”中的每个元素制作一个该结构的实例。

Here is my code: 这是我的代码:

#include <iostream>
using namespace std;

struct element
{
    string symbol;
    string name;
    float atomicWeight;

};

element periodicTable[119];
periodicTable[1].symbol = "H";
periodicTable[1].name = "Hydrogen";
periodicTable[1].atomicWeight = 1.008;

int main()
{
    cout << periodicTable[1].symbol << periodicTable[1].name << periodicTable[1].atomicWeight << endl;

    return 0;
}

I run linux, and when I try to compile this I get this error: 'error: periodicTable does not have a type' 我运行linux,当我尝试编译它时,出现以下错误:“错误:periodicTable没有类型”

I would like to know how to make an array of structs correctly, and if anyone has a better way to make a program like this or see any other errors by all means let me know. 我想知道如何正确地构造一个结构数组,并且如果有人有更好的方法来制作这样的程序,或者一定要看看其他错误,请告诉我。

You cannot use assignments (or any other statements, for that matter) outside of functions. 您不能在函数外部使用赋值(或其他任何语句)。 Use initializers instead: 改用初始化器:

element periodicTable[119] = {
    {"H",  "Hydrogen", 1.008}
,   {"He", "Helium",   4.003}
,   ...
};

Also note that C++ arrays are indexed starting from zero, not from one, so the initial element of the array is periodicTable[0] , not periodicTable[1] . 还要注意,C ++数组是从零开始索引的,而不是从1开始的索引,因此数组的初始元素是periodicTable[0] ,而不是periodicTable[1]

Using global variables is not a good idea except that you have a strong reason. 使用全局变量不是一个好主意,除非您有充分的理由。 So normally you can do as below: 因此,通常您可以执行以下操作:

int main()
{
    element periodicTable[119];
    periodicTable[1].symbol = "H";
    periodicTable[1].name = "Hydrogen";
    periodicTable[1].atomicWeight = 1.008;
    cout << periodicTable[1].symbol << periodicTable[1].name << periodicTable[1].atomicWeight << endl;

    return 0;
}

If you really want to use the global variable, you can do like this: 如果您确实要使用全局变量,则可以执行以下操作:

#include <iostream>
using namespace std;

struct element
{
    string symbol;
    string name;
    float atomicWeight;

};

element periodicTable[119]{
    {},
    {"H", "Hydrogen", 1.008f},   // 1.008 is double, 1.008f is float
};

int main()
{
    cout << periodicTable[1].symbol << periodicTable[1].name << periodicTable[1].atomicWeight << endl;

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM