如何初始化静态向量成员

How to initialize static vector member?

本文关键字:向量 成员 静态 初始化      更新时间:2023-10-16

例如

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

但是,我的编译器不支持初始化列表。有什么方法可以轻松实现它吗?lambda 函数在这里有帮助吗?

有什么方法可以轻松实现它吗?

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

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

我总是担心因为这样的问题在这里被初始化排序而被击落,但是..

#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... 中的任何内容不符合类型或类型转换,这应该在编译时出现。当然,如果你有可变参数模板,你很可能也有初始值设定项列表,但如果没有别的,它会使大脑食物变得有趣。

为向量编写一个简单的 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));