在 C++ 创建结构数组
本文将演示关于如何在 C++ 中创建结构体数组的多种方法。
使用 C 风格数组声明来创建固定长度的结构体数组
固定长度的结构数组可以使用 C 式数组符号 []
来声明。在本例中,我们定义了一个名为 Company
的任意结构体,有多个数据成员,并初始化了 2 个元素的数组。这种方法唯一的缺点是,声明的数组是一个没有任何内置函数的原始对象。从好的方面看,它是可以比 C++ 库容器更有效、更快速的数据结构。
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::endl;
using std::vector; using std::string;
struct Company{
string name;
string ceo;
float income;
int employess;
};
int main(){
Company comp_arr[2] = {{"Intel", "Bob Swan", 91213.11, 110823},
{"Apple", "Tim Cook", 131231.11, 137031}};
for (const auto &arr : comp_arr) {
cout << "Name: " << arr.name << endl
<< "CEO: " << arr.ceo << endl
<< "Income: " << arr.income << endl
<< "Employees: " << arr.employess << endl << endl;
}
return EXIT_SUCCESS;
}
输出:
Name: Intel
CEO: Bob Swan
Income: 91213.1
Employees: 110823
Name: Apple
CEO: Tim Cook
Income: 131231
Employees: 137031
使用 std::vector
和 Initializer List 构造函数来创建可变长度的结构体数组
或者,我们可以利用 std::vector
容器来声明一个变量数组,该数组为数据操作提供了多种内置方法。std::vector
对象的初始化方法与前面的例子相同。新元素可以使用传统的 push_back
方法添加到数组中,最后一个元素可以使用 pop_back
删除。在这个例子中,元素被一个一个打印到控制台。
请注意,初始化列表成员必须包括外侧的大括号,以保证正确的分配和格式化。
#include <iostream>
#include <string>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
using std::string;
struct Company{
string name;
string ceo;
float income;
int employess;
};
int main(){
vector<Company> comp_arr = {{"Intel", "Bob Swan", 91213.11, 110823},
{"Apple", "Tim Cook", 131231.11, 137031}};
for (const auto &arr : comp_arr) {
cout << "Name: " << arr.name << endl
<< "CEO: " << arr.ceo << endl
<< "Income: " << arr.income << endl
<< "Employees: " << arr.employess << endl << endl;
}
return EXIT_SUCCESS;
}
输出:
Name: Intel
CEO: Bob Swan
Income: 91213.1
Employees: 110823
Name: Apple
CEO: Tim Cook
Income: 131231
Employees: 137031
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn