基于用户输入的2D动态数组

时间:2018-09-16 07:19:41

标签: c++ arrays visual-c++ multidimensional-array dynamic

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

例如:

4
4
6
5
3

总共4个房间,第一个房间有4人,第二个房间有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;
}

1 个答案:

答案 0 :(得分:1)

使用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() << " persons\n";
    }
}

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