在 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