Array of a Struct C++

Array of a Struct C++

本文关键字:C++ Struct of Array      更新时间:2023-10-16

我已经创建了struct,现在我需要为相应的struct创建一个数组。有人能告诉我怎么做吗?我在网上看的东西,不能真正理解它,所以谁能给我一个例子和解释如何创建一个结构的数组。

 struct CANDIDATE{
    string candiFN;
    string candiLN;
    int partyID;
    int votes;  
};

与创建任何数组的方法相同。下面创建一个长度为5的数组。

CANDIDATE foo [5];

然后你可以随意填充

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

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;
}

请注意,在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);
}

您可以简单地这样做:

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

你可以创建一个值数组

CANDIDATE foo[5];

或指针数组

CANDIDATE* foo = new CANDIDATE[5];

第一个在堆栈中,第二个在堆中,需要手动删除

无论如何考虑使用std::vector