从文件中读取并写入2D矢量

时间:2015-04-28 15:03:48

标签: c++ vector 2d maze

当我试图打印我的2D矢量时,它只读取第3行(这是迷宫的第一行)并忽略其余的迷宫。我的迷宫是这样的;

11
11
X XXXXXXXXX
X X 1     X
X XXXXX X X
X     X X 1
XXXXX XXX X
X X   X   X
X X XXX X X
X X     X X
X XXXXXXX X
X         X
XXXXXXXXXXX 

但我的最终结果就是像那样重写第一行;

11
11
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX

显然我在我的while循环中误会了一些事情......

#include <iostream>
#include <stdio.h>
#include "Maze.h"
#include "hw2.cpp"

void PrintVec2D(vector< vector< char> > &v)
{
    for (size_t i=0; i<v.size(); i++)
    {
        for(size_t j=0; j<v[i].size(); j++)
            cout << v[i][j];

        cout << '\n';
    }
}

void PrintVec1D(vector<char> &v)
{
    for (size_t i=0; i<v.size(); i++)
        cout<< v[i];
}

int main(int argc, char *argv[]){

    string line;
    ifstream myfile (argv[1]);

    if (myfile.is_open())
    {
        //read just first two lines for rows and cols
        string firstline;
        getline(myfile, firstline);
        int rows = std::stoi(firstline);

        string secondline;
        getline(myfile, secondline);
        int cols=std::stoi(secondline);

        //create 2d vector
        vector< vector<char> > _maze;

        //read rest of the file for maze structure
        //I think my problem is in this while loop...
        string line2;
        int ra = 0;
        int rb = 0;

        while(ra<cols)
        {
            getline(myfile, line2);
            vector<char> newRow(line2.begin(),line2.end());

            while (rb<rows)
            {
                _maze.push_back(newRow);
                ra++;
                rb++;
            }
        }

        PrintVec2D(_maze);
        myfile.close();
    }

    else cerr << "Unable to open file";
    return 0;
}

1 个答案:

答案 0 :(得分:1)

你的循环应如下所示:

for(size_t ra = 0; ra < cols; ++ra)
{
    std::string line;

    if(std::getline(myfile, line))
    {
        vector<char> newRow(line.begin(), line.end());
        _maze.push_back(newRow);
        // or just _maze.emplace_back(line.begin(), line.end());
    }
}

我无法找到第二个循环和rb变量的用法。由于newRow已经是一个数组,为每一行添加它的重点是什么?