如何在 C++ 中初始化向量
本文将介绍如何在 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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。