问题描述
我对C ++有点陌生,想通过尝试一个特定的项目来学习更多。这个项目是一个更大的项目,在这里我想测试一些数值方法“函数”对数组大小之类参数的依赖性。我认为组织代码的最佳方法是创建
// implement.h
#include <cmath>
struct input_params{
int input_array_size;
// other parameters
}
void function(float*,float*,input_params);
// implement.cpp
#include <cmath>
#include "implement.h"
void function(float *input,float *output,input_params args){
// do stuff
}
#include "config.h"
input_params args;
#include "implement.h"
#include "config.h"
input_params args;
args.input_array_size = 100; // something I would change before compile time
- 将实际运行代码的脚本
#include <cmath>
#include "implement.h"
#include "config.h"
// float *input = new [arg.input_array_size];
float input[arg.input_array_size]; // I want to make this stack-allocated for performance reasons
// float *output = new [arg.output_array_size];
float output[arg.output_array_size];
function(input,output,args);
我的问题如下:
解决方法
最简单的方法是使您的配置文件创建宏:
// config.h
#define ARG_INPUT_SIZE 100
#define ARG_OUTPUT_SIZE 300
// some_other_file.c
#include "config.h"
float input[ARG_INPUT_SIZE];
float output[ARG_OUTPUT_SIZE];
在bss vs堆中分配它实际上对任何性能指标都非常有意义。
,
- “实际上有没有更好的替代方法?”
当然有。只需使用std::vector<float>
作为输入/输出参数。您可以根据需要动态调整它们的必要大小。
如果您仍然希望使用固定大小,并在编译时执行此操作,则可以使用std::array<float,MY_SIZE>
并使用g ++的-D
命令行选项来定义所需大小:
g++ -D MY_SIZE=100 ...
std::vector
和std::array
比原始的c样式数组或指针要容易得多。
示例代码:
#include <array>
using inarray_t = std::array<float,MY_INPUT_SIZE>;
using outarray_t = std::array<float,MY_OUTPUT_SIZE>;
// Change the signature of your function
void function(inarray_t&,outarray_t&,input_params);
// ...
int main() {
// ...
inarray_t input; // this is stack-allocated for performance reasons
outarray_t output; // this is stack-allocated for performance reasons
// ...
}
请注意,堆栈分配不会超出堆栈大小限制,通常不会那么大,并且您很快就会遇到堆栈溢出(无双关)的情况。