如何在 C++ 中初始化向量
Jinku Hu
2020年10月15日
本文將介紹如何在 C++ 中用常量值初始化向量。
在 C++ 中使用初始化器列表符號為向量元素賦定值
這個方法從 C++11 風格開始就被支援,相對來說,它是恆定初始化 vector
變數的最易讀的方法。值被指定為一個 braced-init-list
,它的前面是賦值運算子。這種記法通常被稱為複製列表初始化。
#include <iostream>
#include <vector>
using std::cout; using std::cin;
using std::endl; using std::vector;
using std::string;
int main() {
vector<string> arr = {"one", "two", "three", "four"};
for (const auto &item : arr) {
cout << item << "; ";
}
return EXIT_SUCCESS;
}
輸出:
one; two; three; four;
另一個方法是在宣告 vector
變數時使用初始化-列表建構函式呼叫,如下面的程式碼塊所示。
#include <iostream>
#include <vector>
using std::cout; using std::cin;
using std::endl; using std::vector;
using std::string;
int main() {
vector<string> arr{"one", "two", "three", "four"};
for (const auto &item : arr) {
cout << item << "; ";
}
return EXIT_SUCCESS;
}
預處理程式巨集是實現初始化列表符號的另一種方式。在本例中,我們將常量元素值定義為 INIT
物件類巨集,然後將其賦值給向量 vector
變數,如下所示。
#include <iostream>
#include <vector>
using std::cout; using std::cin;
using std::endl; using std::vector;
using std::string;
#define INIT {"one", "two", "three", "four"}
int main() {
vector<string> arr = INIT;
for (const auto &item : arr) {
cout << item << "; ";
}
return EXIT_SUCCESS;
}
C++11 的初始化列表語法是一個相當強大的工具,可用於例項化複雜結構的向量,下面的程式碼示例就證明了這一點。
#include <iostream>
#include <vector>
using std::cout; using std::cin;
using std::endl; using std::vector;
using std::string;
struct cpu {
string company;
string uarch;
int year;
} typedef cpu;
int main() {
vector<cpu> arr = {{"Intel", "Willow Cove", 2020},
{"Arm", "Poseidon", 2021},
{"Apple", "Vortex", 2018},
{"Marvell", "Triton", 2020}};
for (const auto &item : arr) {
cout << item.company << " - "
<< item.uarch << " - "
<< item.year << endl;
}
return EXIT_SUCCESS;
}
輸出:
Intel - Willow Cove - 2020
Arm - Poseidon - 2021
Apple - Vortex - 2018
Marvell - Triton - 2020
Author: Jinku Hu
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