简体   繁体   English

C ++结构的数组

[英]Array of a Struct C++

I have made struct and now I need to create an array for the corresponding struct. 我已经构造好了结构,现在我需要为相应的结构创建一个数组。 Could anyone help me how to go about that? 谁能帮我解决这个问题? I have looked at stuff online and couldn't really understand it, so could anyone give me an example and explanation on how to create an array of a struct. 我在网上看过东西,但并不太了解,所以有人可以给我一个示例和有关如何创建结构数组的说明。

 struct CANDIDATE{

    string candiFN;
    string candiLN;
    int partyID;
    int votes;  

};

The same way you make any array. 制作任何数组的方式相同。 The following makes an array of length 5. 下面是长度为5的数组。

CANDIDATE foo [5];

Then you can fill it however you'd like 然后,您可以根据需要填写它

for (unsigned int i = 0; i < 5; ++i)
{
    CANDIDATE temp("first", "second", 1, 2);
    foo[i] = temp;
}

Or 要么

for (unsigned int i = 0; i < 5; ++i)
{
    CANDIDATE temp;
    temp.candiFN = "first";
    temp.candiLN = "second";
    temp.partyID = 1;
    temp.votes = 2;
    foo[i] = temp;
}

Note that in C++ using a std::vector introduces more safety and flexibility to most applications. 请注意,在C ++中,使用std::vector可为大多数应用程序带来更多的安全性和灵活性。

std::vector<CANDIDATE> bar;
for (unsigned int i = 0; i < 5; ++i)
{
    CANDIDATE temp("first", "second", 1, 2);
    bar.push_back(temp);
}

You can simply do this: 您可以简单地做到这一点:

struct CANDIDATE{
    string candiFN;
    string candiLN;
    int partyID;
    int votes;  
}array[5];
//just add an array between } and ; 

You can make an array of values 您可以创建一个值数组

CANDIDATE foo[5];

or a pointer array 或指针数组

CANDIDATE* foo = new CANDIDATE[5];

The first goes in the stack, the second in the heap and need manual delete 第一个进入堆栈,第二个进入堆栈,需要手动删除

Anyway consider of use std::vector 无论如何考虑使用std::vector

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

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