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