首页 > 解决方案 > 如何在 C++ 中创建具有不同行大小的向量?

问题描述

例如,如果我从用户那里获取 n=9 输入。输入为 = {2 3 1 1 2 5 2 7 8} 我的向量应如下所示:-

    2 3 1 1 2
    2 7 8

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

标签: c++vector2d

解决方案


这里有两个解决方案。

第一个检查 5 并在满足某些条件时添加一行以确定是否要添加新行。

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

解决方案1:

#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 

解决方案2:

#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 

推荐阅读