用c ++填充静态成员容器

Mal*_*eev 11 c++ stl

我有一个静态类成员,它是一些容器,就像

(foo.h中)

class Foo
{
   ...
private:
   static list<string> s_List;
}
Run Code Online (Sandbox Code Playgroud)

我需要使用许多特定值填充列表.实际上它也应该是const,但这可能会使问题进一步复杂化.所有类成员函数都是静态的,因此在构造函数中初始化它是没有意义的.

Ida*_*n K 15

一个常见的解决方案是做这样的事情:

// header
class Foo
{
...
private:
   static list<string> s_List;
}

// cpp
list<string> init()
{
     list<string> tmp;
     ... fill tmp with strings

     return tmp;
 }

 list<string> Foo::s_List(init());
Run Code Online (Sandbox Code Playgroud)

另一种方法就像Neil Butterworth建议的那样.


小智 8

另一种方法是创建一个简单的初始化类:

list <string> Foo::s_List;

struct Init {
   Init() {
      Foo::s_List.insert("apple");
      Foo::s_List.insert("bannana");
      Foo::s_List.insert("grapes");
   }
};

static Init doInit;
Run Code Online (Sandbox Code Playgroud)

请注意,由于列表是私有的,这可能需要您使Init成为Foo的朋友.将这些类包含在它们初始化的类中通常也很方便.

但是,我只是重新阅读你的问题,另一个想法发生 - 如果列表是const,你可能不会改变它,在这种情况下,一个简单的字符串数组,用排序顺序的字符串初始化可能是一个更好的解决方案.搜索(使用std :: binary_search)肯定比列表更快,当然可以很容易地进行初始化.

  • 订单在同一编译单元中得到保证. (3认同)
  • 好主意.它保证可以工作,因为静态成员和全局变量在每个源文件中按顺序初始化.由于列表在原始问题中是私有的,因此需要朋友声明. (2认同)

Jef*_*ant 6

如果您的编译器支持 C++0x,那么这实际上很容易完成。

#include <iostream>
#include <list>

class Foo
{
public:
   static std::list<std::string> s_List;
};

std::list<std::string> Foo::s_List = {"hello", "world", "asdf", "qwerty"};

int main()
{
    for(const std::string& str : Foo::s_List)
        std::cout << str << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这适用于 const 和非常量静态成员。我已经使用 clang-4.2、gcc-4.7、gcc-4.6 和 gcc-4.5 测试了此代码片段。Gcc-4.5 不支持更新的for语法,因此您必须使用带有迭代器的传统for循环。另外,不要忘记将-std=c++0x标志传递给编译器。我相当有信心 Visual Studio 也支持此功能,但我不确定也不知道哪些版本。