46

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

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

这是一个示例代码:)

push_back() 中的值是独立声明的;不在数组或其他东西中。

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

4

6 回答 6

53

在 C++03 中,最简单的方法是使用工厂函数:

std::vector<int> MakeVector()
{
    std::vector v;
    v.push_back(4);
    v.push_back(17);
    v.push_back(20);
    return v;
}

std::vector Foo::MyVector = MakeVector(); // can be const if you like

“返回值优化”应该意味着数组被填充到位,而不是复制,如果这是一个问题。或者,您可以从数组初始化:

int a[] = {4,17,20};
std::vector Foo::MyVector(a, a + (sizeof a / sizeof a[0]));

如果您不介意使用非标准库,可以使用 Boost.Assignment:

#include <boost/assign/list_of.hpp>

std::vector Foo::MyVector = boost::list_of(4,17,20);

在 C++11 或更高版本中,您可以使用大括号初始化:

std::vector Foo::MyVector = {4,17,20};
于 2010-09-13T16:23:07.607 回答
28

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

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

这样,您也可以制作静态常量,以避免意外修改。

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

// Foo.h

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

// Foo.cc

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

在 C++Ox 中,我们将有一种语言机制来做到这一点,使用初始化列表,所以你可以这样做:

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

这里

于 2010-09-13T15:45:11.310 回答
27

使用 C++11:

//The static keyword is only used with the declaration of a static member, 
//inside the class definition, not with the definition of that static member:
std::vector<int> Foo::MyVector = {4, 17, 20};
于 2012-10-25T20:36:46.243 回答
2

你可以试试这个:

int arr[] = { 1,2,3,4,5,6,7,8,9 };
MyVector.insert(MyVector.begin(), arr, &arr[sizeof(arr)/ sizeof(*arr)]);

但它可能只在你有一个非常长的向量时才值得,而且它看起来也不是更好。但是,您摆脱了重复的 push_back() 调用。当然,如果您的值“不在数组中”,则必须先将它们放入其中,但您可以根据上下文静态(或至少引用/指针)执行此操作。

于 2010-09-13T15:48:35.253 回答
2

如何使用静态对象进行初始化。在其构造函数中,它可以调用对象中的静态函数来进行初始化。

于 2012-09-18T01:03:53.253 回答
0

使用 boost,您可以使用在 boost::assign 命名空间中定义的 +=() 运算符。

#include <boost/assign.hpp>

using namespace boost::assign;

int main()
{
    static std::vector<int> MyVector;
    MyVector += 4,17,20;
    return 0;
}

或使用静态初始化:

#include <boost/assign.hpp>

using namespace boost::assign;

static std::vector<int> myVector = list_of(4)(17)(2);

int main()
{
    return 0;
}

甚至更好,如果您的编译器支持 C++ 11,请使用初始化列表。

于 2012-11-24T20:02:38.187 回答