用硬编码元素初始化STD:向量的最简单方法是什么?我可以创建一个数组并像这样初始化它:int a[] = {10, 20, 30};如何创建std::vector并初始化它同样优雅?我所知道的最好的方法是:std::vector<int> ints;ints.push_back(10);ints.push_back(20);ints.push_back(30);有更好的办法吗?
3 回答
白衣染霜花
TA贡献1796条经验 获得超10个赞
static const int arr[] = {16,2,77,29};vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
慕妹3242003
TA贡献1824条经验 获得超6个赞
std::vector<int> v = {1, 2, 3, 4};
#include <boost/assign/list_of.hpp>...std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);
#include <boost/assign/std/vector.hpp>using namespace boost::assign;...std::vector<int> v;v += 1, 2, 3, 4;
list_of
std::deque
12345678_0001
TA贡献1802条经验 获得超5个赞
int tmp[] = { 10, 20, 30 };std::vector<int> v( tmp, tmp+3 ); // use some utility to avoid hardcoding the size here
vector<int> v = list_of(10)(20)(30);
// option 1, typesafe, not a compile time constanttemplate <typename T, std::size_t N>inline std::size_t size_of_array( T (&)[N] ) { return N;}// option 2, not typesafe, compile time constant#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))// option 3, typesafe, compile time constanttemplate <typename T, std::size_t N>char (&sizeof_array( T(&)[N] ))[N]; // declared, undefined#define ARRAY_SIZE(x) sizeof(sizeof_array(x))
- 3 回答
- 0 关注
- 370 浏览
添加回答
举报
0/150
提交
取消