向量<int>a[n] 分配在堆栈还是堆中?声明 vector<vector<int>>a(n) 和 vector<int>a[n] 之间的区别? [英] vector&lt;int&gt; a[n] allocated in stack or heap? Difference between the declarations vector&lt;vector&lt;int&gt;&gt;a(n) and vector&lt;int&gt;a[n]?

查看:35
本文介绍了向量<int>a[n] 分配在堆栈还是堆中?声明 vector<vector<int>>a(n) 和 vector<int>a[n] 之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我声明 vector<向量> a(n),内存在堆中分配,而当我声明它时,vector<;int> a[n],在栈上分配.但为什么?第二个是否意味着方式 - a[i] 是指向第 i 个向量的指针,因为向量是在堆中动态分配的,因此整个分配应该在堆中.不是吗?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆