基于用户输入的 2D 动态阵列

2D Dynamic Array Based on User Input

本文关键字:2D 动态 阵列 输入 于用户 用户      更新时间:2023-10-16

>场景: 从文件中读取数字并相应地创建动态 2D 数组 数据文件的第一行表示房间,其余行表示房间中的人数

例如:

四 4 6 5 3

共4间客房,第1间4人,第2间6人...

到目前为止,这是我的代码,如何检查我是否创建了大小正确的动态数组?

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
ifstream readFirstLine("data.txt");
ifstream readData("data.txt");
string line;
int numRoom, numPerson = 0;
int i = -1;
while (getline(readFirstLine, line))
{
istringstream linestream(line);
if (i == -1)
{
linestream >> numRoom;
cout << "numRoom:" << numRoom << endl;
break;
}
}
readFirstLine.close();
int** numRoomPtr = new int*[numRoom];
while (getline(readData, line))
{
istringstream linestream(line);
if (i == -1)
{
}
else
{
linestream >> numPerson;
numRoomPtr[i] = new int[numPerson];
cout << "i:" << i << endl;
cout << "numPerson:" << numPerson<< endl;
}

i++;
}
readData.close();


return 0;
}

使用std::vector执行当前程序的更好方法可能是这样的:

#include <iostream>
#include <vector>
#include <fstream>
int main()
{
std::ifstream dataFile("data.txt");
// Get the number of "rooms"
unsigned roomCount;
if (!(dataFile >> roomCount))
{
// TODO: Handle error
}
// Create the vector to contain the rooms
std::vector<std::vector<int>> rooms(roomCount);
for (unsigned currentRoom = 0; currentRoom < roomCount; ++currentRoom)
{
unsigned personCount;
if (dataFile >> personCount)
{
rooms[currentRoom].resize(personCount);
}
else
{
// TODO: Handle error
}
}
// Don't need the file anymore
dataFile.close();
// Print the data
std::cout << "Number of rooms: " << rooms.size() << 'n';
for (unsigned currentRoom = 0; currentRoom < rooms.size(); ++currentRoom)
{
std::cout << "Room #" << currentRoom + 1 << ": " << rooms[currentRoom].size() << " personsn";
}
}

如您所见,现在可以在完成文件读取后获取数据的"大小"。