[英]g++: compiling a huge static std::vector
I have generated a sorted list of about 117000 English words, which I have put into a std::vector<std::string>
in a C++ header file, like so:我已经生成了一个大约 117000 个英语单词的排序列表,我将其放入 C++ 头文件中的
std::vector<std::string>
中,如下所示:
#ifndef WORDS_HPP
#define WORDS_HPP
#include <vector>
#include <string>
const std::vector<std::string> words{
"a",
"a\'s",
"aa",
"aa\'s",
"aaa",
/* >100k lines omitted */
"zyuganov",
"zyuganov\'s",
"zzz"
};
#endif
When including this monstrosity in a .cpp file and compiling the thing with g++ (Debian 4.9.2-10) 4.9.2, the compiler causes my system to run out of memory.当在 .cpp 文件中包含这个怪物并用 g++ (Debian 4.9.2-10) 4.9.2 编译它时,编译器导致我的系统内存不足。 I only have 4 GB, unfortunately.
不幸的是,我只有 4 GB。
I would like to have the vector compiled statically into my executable (toy project, FYI), but obviously I can't get it to work.我想将向量静态编译到我的可执行文件(玩具项目,仅供参考)中,但显然我无法让它工作。 How do I solve this?
我该如何解决这个问题?
As R Shau says, this is a good solution:正如 R Shau 所说,这是一个很好的解决方案:
char const* words [] = { ... };
It seems that when you initialize a std::string the compiler has to generate a call to the std::string constructor so the memory can be allocated on the heap.似乎当您初始化 std::string 时,编译器必须生成对 std::string 构造函数的调用,以便可以在堆上分配内存。 It doesn't seem to generate any kind of loop ... you get a lot of assembly language out the back.
它似乎没有产生任何类型的循环……你从后面得到了很多汇编语言。
It does a lot better initializing a vector of integers, but still compared to the old C style array it's a lot of overhead.它在初始化整数向量方面做得更好,但与旧的 C 风格数组相比,它仍然有很多开销。
There are also various tricks for embedding arbitrary data into your C/C++ program.还有各种技巧可以将任意数据嵌入到 C/C++ 程序中。 Some references:
一些参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.