静态向量的初始化 [英] Initialisation of static vector

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

问题描述

我不知道初始化静态向量的方式是否比下面更好?

I wonder if there is the "nicer" way of initialising a static vector than below?

class Foo
{
    static std::vector<int> MyVector;
    Foo()
    {
        if (MyVector.empty())
        {
            MyVector.push_back(4);
            MyVector.push_back(17);
            MyVector.push_back(20);
        }
    }
}

这是一个示例代码:)

It's an example code :)

push_back()中的值是独立声明的;

The values in push_back() are declared independly; not in array or something.

编辑:如果不可能,请告诉我:)

if it isn't possible, tell me that also :)

推荐答案

通常,我有一个类用于构建我使用的容器(如这一个从boost),这样你可以:

Typically, I have a class for constructing containers that I use (like this one from boost), such that you can do:

const list<int> primes = list_of(2)(3)(5)(7)(11);

这样,你可以使用静态const,以避免意外修改。

That way, you can make the static const as well, to avoid accidental modifications.

对于静态,你可以在.cc文件中定义:

For a static, you could define this in the .cc file:

// Foo.h

class Foo {
  static const vector<int> something;
}

// Foo.cc

const vector<int> Foo::something = list_of(3)(5);

在C ++ Ox中,我们有一个语言机制来实现这一点,所以你可以这样做:

In C++Ox, we'll have a language mechanism to do this, using initializer lists, so you could just do:

const vector<int> primes({2, 3, 5, 7, 11});

查看此处

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

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