基于用户输入的 2D 动态阵列
2D Dynamic Array Based on User Input
>场景: 从文件中读取数字并相应地创建动态 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";
}
}
如您所见,现在可以在完成文件读取后获取数据的"大小"。
相关文章:
- 基于用户输入的 2D 动态阵列
- 2D 动态阵列被视为特洛伊木马?
- 打印 2D 动态数组 c++ 函数
- 不明白使用双指针 (**) 创建 2d 动态数组
- 英特尔并行工作室 2015 C++中的 2D 动态分配全局阵列
- 如何在C 中的2D动态数组中访问1个元素
- C 类中的2D动态数组
- C 删除并在2D动态阵列中删除和紧凑的行
- C++ 2D 动态阵列分配
- 显示2D动态数组
- 为具有许多友元函数c++的模板类(2d动态)创建析构函数
- 如何防止此 2D 动态数组程序崩溃
- 访问 2D 动态数组的元素 - c++
- 在 2D 动态数组中填充数据
- 填充 2D 动态数组时"无法读取内存"
- 对 2D 动态数组进行排序 C++
- 2D 动态数组程序崩溃
- c++11 使用 std::fill 来填充 2D 动态分配的数组
- 类和 2D 动态数组
- 将一个2d动态数组传递给C++中的一个函数