用硬編碼元素初始化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_ofstd::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 herevector<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 關注
- 409 瀏覽
添加回答
舉報
0/150
提交
取消
