我正在尝试在 C++ 中执行合并排序代码,并且为了避免大量内存使用,我想将辅助向量声明为全局变量。您可能知道,使用全局变量策略,使用的空间是O(1),而使用另一个,它是O(N logN)。但是有一个小问题,我不知道将用于测试我的代码的向量的大小,因此我需要动态分配该全局变量。
我已经尝试做这样的事情:
这是来自 .h 档案:
void mymergesort_recursive(std::vector<int> &v, SortStats &stats, int i = 0,
int f = 0, bool nouveau = true);
int *aux = nullptr;
这是来自 .cpp 档案:
void mymergesort_recursive(std::vector<int> &v, SortStats &stats, int i,
int f, bool nouveau) {
if (nouveau) {
stats.recursive_calls = 1;
f = int(v.size());
// Allocates the variable aux according with the vector size. This makes a lot of memory economy.
aux = new int[f];
} else {
...
}
...
}
其实我也试过这个:
aux = (int *)malloc(f * sizeof(int));
aux = static cast <int*>(malloc(f * sizeof(int)));
以及其他所有导致相同错误的尝试和错误可能性:-(
`aux'的多重定义
我在这里的这个论坛中寻找了一些其他问题,但是尽管有很多类似的问题,但我无法完全解决这个问题。
我想已经清楚地解释了这个问题,但如果有什么不明白的地方,请询问。
错误是您在标题上声明了一个变量。
在标题上你应该放
extern int* aux;
然后在一些 .cpp 中你应该输入:
int* aux= nullptr;
无论如何,你应该认真考虑而不是int* aux
使用std::vector<int> aux;
.
reserve
在使用它之前进行记忆以优化它。delete
/free
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句