简体   繁体   English

列表向量

[英]Vector of lists

So I am trying to write a function that takes two arguments, list<item> myList , and int num_items and creates a vector of new lists. 因此,我试图编写一个带有两个参数list<item> myListint num_items并创建一个新列表的向量。 Each item has data member ID, which is the index in the vector of which list the item should be added to. 每个项目都有数据成员ID,这是该项目应添加到其列表的向量中的索引。 The ID of any item is guaranteed to be no greater than (num_items - 1). 保证任何项目的ID都不大于(num_items-1)。 Here is my code: 这是我的代码:

vector<list<item>> createVector(list<item> myList, int num_items) {
   vector<list<item>> myVector;
   myVector.reserve(num_items);

   for(item& i : myList)
      myVector[i.ID].push_back(i);

   return myVector;
}

This is causing a segmentation fault whenever I try to call push_back() to add an item to a list in the vector. 每当我尝试调用push_back()将项目添加到向量列表中时,这都会导致分段错误。 I know how to implement the function using pointers, however the type returned by the function must be an actual vector of lists not pointers to them, so I can't use dynamic memory allocation. 我知道如何使用指针来实现该函数,但是该函数返回的类型必须是列表的实际向量,而不是指向它们的指针,因此我不能使用动态内存分配。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks. 谢谢。

reserve() merely allocates a block of memory. reserve()仅分配一个内存块。 It does not create the list objects that you are calling push_back() on. 它不会创建您要调用push_back()list对象。 You need to use resize() instead of reserve() to create them: 您需要使用resize()而不是reserve()来创建它们:

myVector.resize(num_items);

Or better, pass the count to the constructor directly instead: 或者更好的是,直接将计数传递给构造函数:

vector<list<item>> myVector(num_items);

reserve only reserves space for that many vector elements; reserve只为那么多向量元素保留空间; it doesn't create any elements, so you can't access them. 它不会创建任何元素,因此您无法访问它们。 You want to use resize (or just pass the size as a constructor argument), to populate the vector with valid, empty lists. 您想使用resize (或只是将size作为构造函数参数传递)来用有效的空列表填充向量。

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

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