簡體   English   中英

如何在 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,第二個解決方案將添加一行,並在處理循環結束時擦除所有空白行。

解決方案 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";
   }
}        

Output:

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";
   }
} 

Output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM