What is the easiest way to initialize a std::vector with hardcoded elements?(使用硬编码元素初始化 std::vector 的最简单方法是什么?)
本文介绍了使用硬编码元素初始化 std::vector 的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以创建一个数组并像这样初始化它:
I can create an array and initialize it like this:
int a[] = {10, 20, 30};
如何创建一个 std::vector
并以同样优雅的方式初始化它?
How do I create a std::vector
and initialize it similarly elegant?
我所知道的最好方法是:
The best way I know is:
std::vector<int> ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);
有更好的方法吗?
推荐答案
一种方法是使用数组来初始化向量
One method would be to use the array to initialize the vector
static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
这篇关于使用硬编码元素初始化 std::vector 的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用硬编码元素初始化 std::vector 的最简单方法是


猜你喜欢
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
- GDB 不显示函数名 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 如何提取 __VA_ARGS__? 2022-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01