如何实现使用 gcc-4.4 编译的大向量初始化?

How to implement large vector initialization that compiles with gcc-4.4?

本文关键字:编译 向量 初始化 gcc-4 何实现 实现      更新时间:2023-10-16

我有一个20k已知字符串的列表,我在编译时知道这些字符串,并且永远不会更改。一种不可配置的字典。我不想在运行时从文件加载它,因为这意味着很多不必要的架构:在某个路径中查找文件,指示路径的配置文件等。

我在C++年提出了这样的解决方案:

在.cpp:

std::vector<std::string> dic;
dic.reserve(20000);
#define VECTOR_DIC_ dic;
#include values.inl
#undef VECTOR_DIC_

然后在 values.inl 中,20k 的 LI push_back调用,如下所示:

VECTOR_DIC_.push_back("string1");
VECTOR_DIC_.push_back("string2");
...
VECTOR_DIC_.push_back("string20000");

这段代码在 Debian 上编译并正确使用 gcc-4.8 工作,但无法使用 gcc-4.4 编译,gcc-4.4 永远不会完成编译 a.cpp 文件。

为什么 gcc-4.4 不支持这种类型的大型初始化?另外,在编译时是否有针对已知值进行如此大初始化的设计模式?

使用一个const char *数组,然后从中初始化你的向量:

#include <string>
#include <vector>
char const * const S[] = {
"string1",
"string2"
};
const std::size_t N_STRINGS = sizeof(S) / sizeof(*S);
const std::vector<std::string> dic(S, S + N_STRINGS);

这在 g++ 4.4.7 中编译得很好(虽然没有使用 20k 字符串进行测试(。

编译器可能会犹豫不决,因为初始化不在函数内部。

若要使其正常工作,请在函数中插入初始值设定项。

如:

std::vector<std::string> dic;  // wouldn't an std::set be a better match?
bool InitDitionary() {
dic.reserve(20000);
#define VECTOR_DIC_ dic;
#include values.inl
#undef VECTOR_DIC_
return true;
}
// you can then call InitDictionary at your discretion from within your app
// or the following line will initialize before the call to main()
bool bInit = InitDictionnary();

或者,静态 const char* 替代方案也是可行的,您必须将字符串文件更改为这种格式,我建议您包含整个声明,因为它可能是由软件生成的。 数组应该事先排序,所以你可以使用 binary_search、upper_bound 等来搜索它。

const char dic[20000] = {  // <-- optional, in the file, so you have the number of items 
"string1",
"string2",
"string3",
"string4",
// ...
};
const size_t DIC_SIZE = sizeof(dic) / sizeof(dic[0]);  // :)

您可以为文件指定.cpp扩展名,也可以包含为:

#include "dictionary.inc"