[英]How to initialize static vector member?
例如
struct A
{
static vector<int> s;
};
vector<int> A::s = {1, 2, 3};
但是,我的編譯器不支持初始化列表。 有什么辦法可以輕松實現嗎? lambda函數在這里有用嗎?
對於像這樣的問題,我總是擔心會因為初始化排序被擊落,但是......
#include <iostream>
#include <vector>
#include <iterator>
struct A
{
static std::vector<int> s;
};
static const int s_data[] = { 1,2,3 };
std::vector<int> A::s(std::begin(s_data), std::end(s_data));
int main()
{
std::copy(A::s.begin(), A::s.end(),
std::ostream_iterator<int>(std::cout, " "));
return 0;
}
產量
1 2 3
因為你可以並不意味着你應該 = P
以最低效的方式贏得獎項:
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
template<typename T>
std::vector<T> v_init(const T& t)
{
return std::vector<T>(1,t);
}
template<typename T, typename... Args>
std::vector<T> v_init(T&& t, Args&&... args)
{
const T values[] = { t, args... };
std::vector<T> v1(std::begin(values), std::end(values));
return v1;
}
struct A
{
static std::vector<int> s;
};
std::vector<int> A::s(v_init(1,2,3,4,5));
int main(int argc, const char *argv[])
{
std::copy(A::s.begin(), A::s.end(), std::ostream_iterator<int>(std::cout, " "));
return 0;
}
產量
1 2 3 4 5
如果T和Args中的任何東西都不符合類型或類型可轉換,那么這應該在編譯時嘔吐。 當然,如果你有可變參數模板賠率,你也有初始化列表,但如果沒有別的話,它會帶來有趣的大腦食物。
有什么辦法可以輕松實現嗎?
沒有什么特別優雅的。 您可以從靜態數組中復制數據,也可以使用函數調用的結果對其進行初始化。 前者可能會使用比你想要的更多的內存,而后者需要一些稍微凌亂的代碼。
Boost有一個庫讓它稍微不那么難看:
#include <boost/assign/list_of.hpp>
vector<int> A::s = boost::assign::list_of(1)(2)(3);
lambda函數在這里有用嗎?
是的,它可以讓你不必為了初始化向量而命名一個函數:
vector<int> A::s = [] {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
return v;
}();
(嚴格來說,這應該有一個顯式的返回類型, []()->vector<int>
,因為lambda主體不僅僅包含一個return
語句。有些編譯器會接受我的版本,我相信它會成為標准的2014年)
為向量寫一個簡單的init函數:
vector<int> init()
{
vector<int> v;
v.reserve(3);
v.push_back(1);
v.push_back(2);
v.push_back(3);
return v;
};
vector<int> A::s = init();
您可以從兩個指針初始化std::vector
int xv[] = {1,2,3,4,5,6,7,8,9};
std::vector<int> x(xv, xv+(sizeof(xv)/sizeof(xv[0])));
您甚至可以在模板函數中考慮這一點:
template<typename T, int n>
std::vector<T> from_array(T (&v)[n]) {
return std::vector<T>(v, v+n);
}
另一個想法:
struct A
{
static std::vector<int> s;
};
std::vector<int> A::s;
static bool dummy((A::s.push_back(1), A::s.push_back(2), A::s.push_back(3), false));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.