从 2D 向量中取出一行并将其放入新的 int 中?

Take a row from 2D vector and make it into new int?

我有以下二维数组

54 65 22 34 11
43 12 44 22

我有以下向量语法:

vector<vector<int>> data;

vector<int> row_1 = data[0]; // return 54 65 22 34 11
vector<int> row_2 = data[1]; // return 43 12 44 22

有什么方法可以将 row_1 和 row_2 向量变成这样:

int *row_1 = new int[5] // return 54 65 22 34 11
int *row_2 = new int[4] // return 43 12 44 22

谢谢。

确保向量与您尝试将其存储为的新 int 数组相同。可能最好用 row_1 向量大小分配它:

vector<int> row_1_vec = data[0]; // return 54 65 22 34 11
vector<int> row_2_vec = data[1]; // return 43 12 44 22

int* row_1 = new int[row_1_vec.size()];
int* row_2 = new int[row_2_vec.size()];

现在遍历向量:

for(int val = 0; val < row_1_vec.size(); val++)
{
  row_1[val] = row_1_vec[val];
}

for(int val = 0; val < row_2_vec.size(); val++)
{
  row_2[val] = row_2_vec[val];
}

确保在使用完 row_1 和 row_2 后通过

删除它
delete[] row_1;
delete[] row_2;

根本不需要 new[] 您要实现的目标。

只需要使用 std::vector<std::vector<int>>std::istringstream 来解析输入中的每个整数。

#include <vector>
#include <sstream>
#include <string>
#include <iostream>

int main()
{
   std::vector<std::vector<int>> vRow;
   std::string line;
   int num;
   while (std::getline(cin, line))  // get a line of data
   {
      // add an empty row to the vector 
      vRow.push_back({}); 

      //parse the numbers   
      std::istringstream strm(line);
      while ( strm >> num )
         vRow.back().push_back(num);  // add new number to last row added
   }

   // Output results
   for (auto& v : vRow)
   {
      for (auto& v2 : v )
        std::cout << v2 << " ";
      std::cout << "\n";
   }
}

Live Example

如果你以后想对第一行进行排序,例如,你这样做:

std::sort(vRow[0].begin(), vRow[0].end());