如何在 C++ 中创建具有不同行大小的向量?

How do I create a vector in c++ with different row size?

例如,如果我从用户那里获取 n=9 个输入。 输入 = {2 3 1 1 2 5 2 7 8} 我的向量应该是这样的:-

    2 3 1 1 2
    2 7 8

也就是说,一个向量有2行不同的编号。行中的元素。我想跳过将 5 添加到我的矢量。 如何才能做到这一点? 理想情况下,它不应该有任何空行。即使出现两个连续的 5,或者序列以 5 开始或结束,也不应该有空行。

这里有两种解决方法。

首先检查 5 并在满足特定条件时添加一行以确定是否要添加新行。

第二个解决方案如果找到 5,则添加一行,并在处理循环结束时,擦除所有空白行。

解决方案一:

#include <iostream>
#include <vector>

int main()
{
  std::vector<int> test = {2, 5, 5, 5, 5, 3, 1, 1, 2, 5, 2, 7, 8};

   // Always add an initial first row
   std::vector<std::vector<int>> v2d(1);
   for (auto v : test )
   {
     if ( v != 5 )
         v2d.back().push_back(v);  // add value to the current last row
     else
     {
        // the value is a 5.  Check if we need to skip adding this row
        if ( !v2d.back().empty() )        

          // add a new blank row
          v2d.push_back({});
     }
   }

   // if last row is blank, remove it.
   if ( v2d.back().empty() )
      v2d.pop_back();

   // output results
   std::cout << "The number of rows is " << v2d.size() << "\n";
   for ( auto& v1 : v2d )
   {
     for (auto v : v1 )
        std::cout << v << " ";
    std::cout << "\n";
   }
}        

输出:

The number of rows is 3
2 
3 1 1 2 
2 7 8 

方案二:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
   std::vector<int> test = {2, 5, 5, 5, 5, 3, 1, 1, 2, 5, 2, 7, 8};
   std::vector<std::vector<int>> v2d(1);
   for (auto v : test )
   {
     // Add a new row if it is a 5
     if ( v == 5 )
          v2d.push_back({});
     else
          v2d.back().push_back(v);  // add to current last row
   }

   // remove all the blank rows
   v2d.erase(std::remove_if(v2d.begin(), v2d.end(), [&](const std::vector<int>& v) { return v.empty(); }), v2d.end());

   // output results
   std::cout << "The number of rows is " << v2d.size() << "\n";
   for ( auto& v1 : v2d )
   {
     for (auto v : v1 )
        std::cout << v << " ";
    std::cout << "\n";
   }
} 

输出:

The number of rows is 3
2 
3 1 1 2 
2 7 8