Array of a Struct C++
Array of a Struct C++
我已经创建了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
相关文章:
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- C++Union/Struct位域的实现和可移植性
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- struct.error:解压缩 C++ 结构时,解包需要 288 字节的缓冲区
- 错误:"Left of getValue must have class/struct/union"
- 在 SVM-Struct 中未定义对 sqrt 的引用(已使用 -lm)
- 数据类型"struct seq<0, 1, 2>{}"含义是什么?
- 附加使用 Struct 作为"multikey"并将 std::vector 用作映射值的映射
- QML/C++/QObject Struct Copy
- 如何在 cpp 中解压缩数字,如果它们是使用 struct.pack(fmt, v1, v2, ..) 打包在 pyth
- Msgpack能否提供更好的性能和与Python的struct.pack()相同的功能?
- 将向量传递给<struct> Lua 表
- MPI_DOUBLE_INT and C++ struct
- C++ 中的"template <typename From, typename Tag> struct Alias;"是什么?
- 如何使用Struct打印交换函数
- 返回类型为struct的函数每次调用时都不返回任何内容
- 对struct::struct的未定义引用是什么意思
- 在c++Primer中使用Struct和Vector时出现错误C2661