如何初始化静态向量成员? [英] How to initialize static vector member?

查看:146
本文介绍了如何初始化静态向量成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

struct A
{
    static vector<int> s;
};

vector<int> A::s = {1, 2, 3};

但是,我的编译器不支持初始化列表。任何方式来实现它很容易? lambda函数有帮助吗?

However, my compiler doesn't support initialization list. Any way to implement it easily? Does lambda function help here?

推荐答案


b $ b

Any way to implement it easily?

没有什么特别优雅的。您可以从静态数组复制数据,也可以使用函数调用的结果初始化它。前者可能会使用更多的内存,而后者需要一些稍微杂乱的代码。

There's nothing particularly elegant. You can either copy the data from a static array, or initialise it with the result of a function call. The former might use more memory than you'd like, and the latter needs some slightly messy code.

Boost有一个图书馆,使其略显丑陋:

Boost has a library to make that slightly less ugly:

#include <boost/assign/list_of.hpp>
vector<int> A::s = boost::assign::list_of(1)(2)(3);




lambda函数有帮助吗?

Does lambda function help here?

是的,它可以让你不必为一个函数命名一个初始化向量:

Yes, it can save you from having to name a function just to initialise the vector:

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年成为标准。)

(Strictly speaking, this should have an explicit return type, []()->vector<int>, since the lambda body contains more than just a return statement. Some compilers will accept my version, and I believe it will become standard in 2014.)

这篇关于如何初始化静态向量成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆