简体   繁体   English

用向量向量的元素初始化向量的空向量

[英]Initialize empty vector of vectors with elements of vector of vectors

I have a function which shall initialize an empty vector of vectors from type string with certain elements from an given vector of vectors from type string.我有一个函数,该函数应使用来自字符串类型的给定向量向量中的某些元素初始化来自字符串类型的向量的空向量。 My syntax looks like this我的语法是这样的

std::vector<std::vector<std::string>> extract_data_on_userid(const std::vector<std::vector<std::string>> &array, std::vector<std::string> &user_ids, const int nr_of_events)
{
  std::vector<std::vector<std::string>> data_extract;
  int event_iterator = 0;
  int user_id_iterator = 0;

  // While loops which extracts the events based on user IDs
  while (event_iterator <= nr_of_events)
  {
    // While loop which finds specified user id in an event
    while (user_id_iterator < array[0].size())
    {
      if (check_id(user_ids, array[0][user_id_iterator]))
      {
        for (size_t i = 0; i < array.size(); i++)
        {
          data_extract[i].push_back(array[i][user_id_iterator]);
        }
      }
      user_id_iterator++;
    }

    event_iterator++;
  }

  return data_extract;
}

The given vector consists on varying number of string vectors (at least 2).给定的向量由不同数量的字符串向量(至少 2 个)组成。 My method shall search for certain UserIDs in我的方法将在

check_id(user_ids, array[0][user_id_iterator])

an then push the relevant event (user_id_iterator) in a new 2D Vector for all 1D Vectors然后在所有一维向量的新二维向量中推送相关事件(user_id_iterator)

vector[i:in][user_id_iterator]

Into the newly initiated vector进入新启动的向量

std::vector<std::vector<std::string>> data_extract;

over the for loop.在 for 循环中。

 for (size_t i = 0; i < array.size(); i++)
    {
      data_extract[i].push_back(array[i][user_id_iterator]);
    }

It all does work as expected until the elements of the vectors[i:in] in row [user_id_iterator] shall be pushed into the emtpy vectors.这一切都按预期工作,直到行 [user_id_iterator] 中的向量 [i:in] 的元素应被推送到空向量中。

Do I intially have to initialize all 1D vectors in the 2D Vector data_extract?我最初是否必须初始化 2D Vector data_extract 中的所有 1D 向量? What is the correct syntax to fill an empty vector of vectors which certain elements from a filled vector of vectors?填充向量的空向量的正确语法是什么,其中某些元素来自向量的填充向量? I receive an exception (segmentation fault) because the emtpy vector is not initialized correctly.我收到异常(分段错误),因为 emtpy 向量未正确初始化。

You made a simple error, which is easy to fix.你犯了一个简单的错误,很容易修复。

Your 2 dimensional vector你的二维向量

std::vector<std::vector<std::string>> data_extract;

is empty, after the definition.是空的,在定义之后。 That means, it does not contain any element, in no dimension.这意味着,它不包含任何元素,没有维度。 Even not an element with an index [0] or [0][0] .即使不是具有索引[0][0][0]的元素。 So, you got a segfault, because you were accessing the element [i] , which is not existing.因此,您遇到了段错误,因为您正在访问不存在的元素[i]

So, yes, as you assumed, you have to initialize the vector.所以,是的,正如您所假设的,您必须初始化向量。 There are several possibilities.有几种可能性。 You can set the initial size using the std::vector constructor described here .您可以使用此处描述的std::vector构造函数设置初始大小。 Number 3) or 4)数字 3) 或 4)

So for example:例如:

std::vector<std::vector<std::string>> data_extract(array.size());

Which is probably the most approriate solution.这可能是最合适的解决方案。

You can also resize your vector after the definition您还可以在定义后resize矢量的resize

data_extract.resize(array.size());

but that is an additional line of code, not needed, because you can do in the constructor.但这是额外的一行代码,不需要,因为您可以在构造函数中执行。 You can of course also initialize both dimension of your vector, if you know the size of the second dimension.如果您知道第二个维度的大小,您当然也可以初始化向量的两个维度。

std::vector<std::vector<std::string>> data_extract(array.size(),std::vector<std::string>(array[0].size(),""));

By the way.顺便一提。 Your outer while loop is a no-op.您的外部 while 循环是空操作。

while (event_iterator <= nr_of_events)

The "event_iterator" is used nowhere in the the loop body and the inner while loops will never run. “event_iterator”在循环体中的任何地方都没有使用,内部 while 循环永远不会运行。 This, because in the 2nd round of the outer loop, "user_id_iterator" is already biiger than " array[0].size()" and the inner loop will never run.这是因为在外循环的第二轮中,“user_id_iterator”已经比“array[0].size()”大,并且内循环永远不会运行。

Also the rest of the logic is hard to understand.其余的逻辑也很难理解。 I am not sure, why you always refer to "array[0]".我不确定,为什么你总是提到“array[0]”。

Your segmentation fault is hard to find, as you implemented your function way too complex.您的分段错误很难找到,因为您实现的功能太复杂了。 There are some simple refactoring measures, that reduce the noise that is generated here:有一些简单的重构措施可以减少这里产生的噪音:

Calling a vector of string vectors array is realy irritating.调用字符串向量数组的向量真的很烦人。 Instead try renaming and aliasing it (not knowing your context exactly):而是尝试重命名和别名(不完全了解您的上下文):

using TUserIdEvents = std::vector<std::vector<std::string>>;

TUserIdEvents extract_data_on_userid(const TUserIdEvents &eventsOfUserIds, std::vector<std::string> &user_ids, const int nr_of_events)
{
  TUserIdEvents data_extract;

Instead of using a while loop with the variable declaration and iteration outside, you can do it all in a single for loop:您可以在单个for循环中完成所有操作,而不是使用带有变量声明和迭代for while 循环:

// Loop which extracts the events based on user IDs  
for (int event_iterator = 0; event_iterator <= nr_of_events; ++event_iterator)

Your inner while can be replaced with a ranged based for loop, so you don't need to keep track of another int-iterator:您的内部while可以替换为基于范围的 for 循环,因此您无需跟踪另一个 int 迭代器:

// Loop which finds specified user id in an event
for (const auto& userIdsOfEvent : eventsOfUserIds[0])
{
    if (check_id(user_ids, userIdsOfEvent))
    {
       for (size_t i = 0; i < eventsOfUserIds.size(); i++)
       {
          data_extract[i].push_back(userIdsOfEvent);
       }
    }
}

Which brings us to your actual problem:这给我们带来了您的实际问题:

data_extract[i].push_back(array[i][user_id_iterator]);

You are accessing data_extract with the iterator i , but data_extract is not initialized yet on the D1 level.您正在使用迭代器i访问data_extract ,但 data_extract 尚未在 D1 级别初始化。 To do that, you can construct it as follows:为此,您可以按如下方式构建它:

TUserIdEvents data_extract(eventsOfUserIds.size());

This creates an amount of sub vectors within data_extract, equal to the amount of sub vectors passed as parameter.这会在 data_extract 中创建一定数量的子向量,等于作为参数传递的子向量的数量。

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

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