简体   繁体   English

在堆上初始化向量数组,C ++

[英]initializing arrays of vectors on the heap, c++

My goal is to create an array of vectors (with a capacity of 10 integers for each vector) on the heap. 我的目标是在堆上创建向量数组(每个向量的容量为10个整数)。 I can create my array easily enough: 我可以很容易地创建数组:

vector<int>* test = new vector<int>[NUM_VERTS];

However, this creates an array of empty vectors. 但是,这将创建一个空向量数组。 I know each vector will store at least 10 ints and so I want to create the vectors with size 10 to start with to avoid having them re-size themselves multiple times (I'm reading in a big file and so efficiency is important). 我知道每个向量将至少存储10个整数,因此我想创建大小为10的向量,以免让它们多次自行调整大小(我正在读取一个大文件,因此效率很重要)。 How can I modify the statement above so that it does what I want? 如何修改上面的语句,以便它可以执行我想要的操作?

As a side note, I'm using VS 2013 and struggling with its debugger. 附带说明一下,我正在使用VS 2013,并且正在努力调试它。 When I run the debugger and look at the contents of test above, it shows me the memory address of the area it points to but not the contents stored at the address. 当我运行调试器并查看上面test的内容时,它显示了它指向的区域的内存地址,但没有显示该地址中存储的内容。 Does anyone know how I can view the contents instead of the address? 有谁知道我如何查看内容而不是地址?

Thanks 谢谢

PS I'm creating the array of vectors on the heap instead of the stack because the array is extremely large (just under a million entries). PS我正在堆上而不是堆栈上创建向量数组,因为该数组非常大(不到一百万个条目)。 When I tried to create it on the stack I got a stack overflow error. 当我尝试在堆栈上创建它时,出现堆栈溢出错误。

You can create a vector of vector s that is not the same as an array but for your use case it should be equivalent: 您可以创建一个vector ,该vector与数组不同,但是对于您的用例,它应该等效:

std::vector< std::vector<int> > test(NUM_VERTS, std::vector<int>(10));

there's no need to allocate it with new because vector elements are already on the heap. 因为vector元素已经在堆中,所以不需要用new分配它。

If you need the pointer to the first contained vector you can just use 如果您需要指向第一个包含向量的指针,则可以使用

std::vector<int> *p = &test[0];

and use p as if it was an heap-allocated array of vectors (all the elements of a vector are guaranteed to be consecutive in memory). 并使用p ,好像它是矢量的堆分配阵列(一个中的所有元素vector保证是在存储器中连续的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM