向量<int>a[n] 分配在堆栈还是堆中?声明 vector<vector<int>>a(n) 和 vector<int>a[n] 之间的区别? [英] vector<int> a[n] allocated in stack or heap? Difference between the declarations vector<vector<int>>a(n) and vector<int>a[n]?
问题描述
当我声明 vector<向量
When I declare vector< vector< int>> a(n), memory is allocated in heap whereas when I declare it vector< int> a[n], it is allocated on stack. But why? Doesn't the second one mean the way- a[i] is a pointer to the i-th vector, as the vectors are dynamically allocated in heap and hence the whole allocation should be in heap. Isn't it?
如果我错了,你能解释一下吗?
Could you please explain me if I am wrong?
推荐答案
vector<int> adj[n];
这不是合法的 C++ 代码,不允许像这样在堆栈上声明动态大小的数组.
This is not legal C++ code, you are not allowed to declare a dynamicaly sized array on the stack like this.
这也可能是您的问题的原因,因为在堆栈上进行如此巨大的分配可能会导致一些重大问题.
It's also probably the cause of your issue, as making such a huge allocation on the stack can cause some major issues.
您应该改用以下内容:
vector<vector<int>> adj(n);
这篇关于向量<int>a[n] 分配在堆栈还是堆中?声明 vector<vector<int>>a(n) 和 vector<int>a[n] 之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!