[英]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
來解析輸入中的每個 integer 即可。
#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";
}
}
例如,如果您稍后要對第一行進行排序,請執行以下操作:
std::sort(vRow[0].begin(), vRow[0].end());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.