亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用硬編碼元素初始化STD:向量的最簡單方法是什么?

用硬編碼元素初始化STD:向量的最簡單方法是什么?

C++
吃雞游戲 2019-06-26 15:09:30
用硬編碼元素初始化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]) );


查看完整回答
反對 回復 2019-06-26
?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

如果編譯器支持C+11,則只需執行以下操作:

std::vector<int> v = {1, 2, 3, 4};

這是GCC版的。截至4.4版..不幸的是,VC+2010在這方面似乎落后了。

或者,Boost.分配庫使用非宏魔術允許以下操作:

#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因此,對于性能關鍵的代碼,最好像Yaco by所說的那樣做。


查看完整回答
反對 回復 2019-06-26
?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

在C+0x中,您將能夠以與數組相同的方式進行操作,但不符合當前標準。

在只有語言支持的情況下,您可以使用:

int tmp[] = { 10, 20, 30 };std::vector<int> v( tmp, tmp+3 ); // use some utility to avoid hardcoding the size here

如果可以添加其他庫,則可以嘗試Boost:As期:

vector<int> v = list_of(10)(20)(30);

為了避免硬編碼數組的大?。?/trans>

// 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))


查看完整回答
反對 回復 2019-06-26
  • 3 回答
  • 0 關注
  • 409 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號