如何实现使用 gcc-4.4 编译的大向量初始化?
How to implement large vector initialization that compiles with gcc-4.4?
我有一个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"
相关文章:
- 将编译时常量向量转换为堆分配版本
- 如何实现使用 gcc-4.4 编译的大向量初始化?
- 索引 2D 向量时'Reference to type const..'编译错误
- 尝试初始化结构向量时出现编译错误
- C++向量迭代器nth_element编译错误
- 在编译时以增量方式构建变量指针的向量
- 向量迭代编译为非常不同的指令
- 编译错误向量排序和联合
- 模板函数,它使用 n_copy 复制前 n 个元素形成一个向量,另一个向量导致编译错误
- 使用GCC v4.8在Ubuntu 14.04上定义C 11中元组向量时的编译错误
- 返回向量<对<字符串,字符串>>会导致 gcc 编译代码 (curlcpp) 崩溃
- 使用带有初始值设定项列表的 Stroustrup PPP 书中的向量时出现编译错误
- 在向量中使用派生的可移动但不可压缩的会导致编译错误
- 将指针指向函数的函数和将默认值作为参数的向量会导致编译错误
- 在编译时使用模板初始化指向数组的指针的常量向量
- 常量引用向量向量<向量<long>>赋值不编译
- 使用 Agner 的向量类库编译多架构代码
- C++在编译时将图像像素嵌入向量中
- 提升元组和 stl 向量编译错误
- 声明/编译向量中的2d向量