C++ 中初始化結構體向量
本文將演示關於如何在 C++ 中初始化一個結構體向量的多種方法。
使用 Initializer List 建構函式在 C++ 中初始化一個結構體向量
初始化器列表是用常量值初始化容器的一種常用方法。這種方法比較適合需要有某種起始狀態的資料結構。下面例子中,由於向量包含了自定義定義的 Person
結構體,所以初始化列表項需要歸入大括號內,並用冒號分隔。請注意,結構體的元素使用 struct.element
符號訪問,並輸出到控制檯。
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::endl;
using std::vector; using std::string;
struct Person{
string name;
string surname;
int age;
};
int main(){
vector<Person> parr1 = {{"John", "Cooper", 32},
{"Theo", "Parrot", 23},
{"Aun", "Chao", 43},
{"Vivien", "Bardot", 67}};
for (const auto &arr : parr1) {
cout << "Name: " << arr.name << endl
<< "Surname: " << arr.surname << endl
<< "Age: " << arr.age << endl;
}
return EXIT_SUCCESS;
}
輸出:
Name: John
Surname: Cooper
Age: 32
Name: Theo
Surname: Parrot
Age: 23
Name: Aun
Surname: Chao
Age: 43
Name: Vivien
Surname: Bardot
Age: 67
在 C++ 中使用 Range 建構函式初始化一個結構體向量
另外,還可以利用 range 建構函式來初始化結構體向量。當需要建立現有向量物件的另一個副本時,這種方法很有用。如下面的程式碼示例所示,我們宣告一個 Person
結構體的 parr3
向量,並用相同型別的 parr1
向量的內容初始化它。
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::endl;
using std::vector; using std::string;
struct Person{
string name;
string surname;
int age;
};
int main(){
vector<Person> parr1 = {{"John", "Cooper", 32},
{"Theo", "Parrot", 23},
{"Kim", "Colbert", 53},
{"Aun", "Chao", 43},
vector<Person> parr3(parr1.begin(), parr1.end());
for (const auto &arr : parr3) {
cout << "Name: " << arr.name << endl
<< "Surname: " << arr.surname << endl
<< "Age: " << arr.age << endl;
}
return EXIT_SUCCESS;
}
輸出:
Name: John
Surname: Cooper
Age: 32
Name: Theo
Surname: Parrot
Age: 23
Name: Kim
Surname: Colbert
Age: 53
Name: Aun
Surname: Chao
Age: 43
使用自定義建構函式在 C++ 中初始化一個結構體向量
另一種解決方案是一個向量特定的建構函式,它提供了一個用給定數量的相同值初始化向量的功能。在這種情況下,我們向建構函式提供型別為結構體 Person
的單一元素和一個任意的數字 3
來初始化物件。
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::endl;
using std::vector; using std::string;
struct Person{
string name;
string surname;
int age;
};
constexpr int NUM = 3;
int main(){
vector<Person> parr4(NUM, {"John", "Cooper", 32});
for (const auto &arr : parr4) {
cout << "Name: " << arr.name << endl
<< "Surname: " << arr.surname << endl
<< "Age: " << arr.age << endl;
}
return EXIT_SUCCESS;
}
輸出:
Name: John
Surname: Cooper
Age: 32
Name: John
Surname: Cooper
Age: 32
Name: John
Surname: Cooper
Age: 32
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