如何在C++中将数据嵌入数组中?
我想在编译时间将数据库加载到数组中:
//a.dat
1 2 3 4 5
int main(){
unsigned int a[5]=f("a.dat");
}
但是我找不到stackoverflow中的简单解决方案。有没有人可以给予办法做到这一点。我想有两种方法:
- 使用程序以硬码样式制作数据库,代码:
a[]={1,2,3,4,5};
- 使用函数读取数据(但在运行时),例如:
a[5]=f("a.dat");
I want to load a database into an array at compile time like:
//a.dat
1 2 3 4 5
int main(){
unsigned int a[5]=f("a.dat");
}
But I can't find a simple solution in StackOverflow. Is there anyone can give a way to make it. I guess there are two ways:
- Use a program to make the database in hard-code style, code:
a[]={1,2,3,4,5};
- use a function to read the data (but that is at runtime), like:
a[5]=f("a.dat");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第三个,但也不理想的选择是
#include
您的数据文件。该解决方案要求您调整数据以在值之间包括一个逗号:
a1.dat:
cpp1:
但是,当然,
n
(值数)和该值的分离和该值的实际值数字不是好的设计 -n
需要更新,以防A.DAT更改中的值数量,可以很容易地忘记。因此,您可能需要选择将整个数组声明移至标题:
A2.DAT:
CPP2:
尽管这不会改变问题,而必须指定某处指定元素的数量(并注意省略
n
在a
的声明中,意味着现在编译器无法执行n
a
中的元素实际上存在n
元素)为了解决这个问题,您可能需要使用
std :: vector
而不是:a3.dat:
cpp3:
std :: embed
inde 上面提到的提案也对此“解决方案”也有一些评论。A third, but also not ideal option would be to
#include
your data file.This solution requires you to adapt your data to include a comma between the values though:
a1.dat:
cpp1:
But of course, the separation between
N
(the number of values) and the actual values for the numbers is not good design -N
needs to be updated in case the number of values in a.dat changes, which could easily be forgotten.You might therefore want to choose to move the whole array declaration to the header:
a2.dat:
cpp2:
Though this doesn't change the problem with having to specify the number of elements somewhere (and note that leaving out the
N
in the declaration ofa
means that now there is no way for the compiler to enforce that there are actuallyN
elements ina
)!To circumvent this, you might want to use an
std::vector
instead:a3.dat:
cpp3:
The
std::embed
proposal mentioned above also has some comments on this "solution":使用具有“ C风格”输出的
XXD
,以转换您的输入以进行合适的“嵌入”:变量名称基于输入文件名,因此请明智地命名源文件。
如果您有“构建管道”,这将变得方便,这可能与makefile一样最小:
不要忘记将生成的
ac
添加到.gitignore
或类似的东西。Use
xxd
that has a "C-style" output, to convert your input for suitable "embedding":The variable names are based on input filename, so name your source files wisely.
This is getting convenient if you have a "build pipeline", which can be as minimal as a Makefile:
Don't forget to add the generated
a.c
into your.gitignore
or something alike.