簡體   English   中英

在C ++中迭代“ char”的2D向量,未打印出空白字符

[英]Iterating over 2D vector of “char” in C++, blank characters are not printing out

我目前正在研究基於文字的戰艦游戲,並且將用於存儲棋盤的容器從2D字符數組轉換為2D向量。 在下面的代碼片段中,我將初始化整個電路板並將其中的所有字符設置為空格。 接下來就是創建板等的所有代碼。

const int width  = 100;
const int height = 35;
vector< vector<char> > buffer(width, vector<char>(height,0));

for (int y = 0; y < height; ++y)
    for (int x = 0; x < width; ++x)
        buffer[x][y] = ' ';

當我要將板子輸出到屏幕上時,我試圖使用為矢量提供的迭代器。 我唯一的問題是,在使用迭代器時,它似乎忽略了向量中的空白,因此游戲板看起來並不像它應該的那樣。 只需使用double for循環遍歷向量,然后輸出就可以了。

vector<vector<char> >::const_iterator row;
vector<char>::const_iterator col;
for (row = buffer.begin(); row != buffer.end(); row++) {
    for (col = row->begin(); col != row->end(); col++) {
            cout << *col;
    }
    cout << endl;
}

這是我第一次嘗試使用陷入困境的向量。 有人知道為什么它會忽略空白字符嗎?

您不需要使用vector<vector<char> >::iterator 向量類為您重載了下標operator[] 所以你可以這樣寫:

for(size_t i = 0; i < height; i++)
{
    for(size_t j = 0; j < width; j++)
    {
        cout << buffer[i][j]; // buffer is a vector<vector<char> >
    }
    cout << "\n";
}

我的第一個問題是:“為什么對簡單的二維數組使用向量?” 我將簡單地使用二維數組並完成它。 通過一次malloc()調用分配一個二維對象數組的有效方法(這樣就可以通過一次free()調用釋放它):

/* set up the memory for a 2D matrix with entries of size "size" */
void** matrix2D(long rows, long columns, long size)
{
    long    i;
    unsigned long long      row_size = (unsigned long long)columns * (unsigned long long)size;
    unsigned long long      data_size = ((unsigned long long)rows * (unsigned long long)columns + 1) * (unsigned long long)size;
    unsigned long long      pointer_size = (unsigned long long)rows * sizeof(void*);
    void**  result;

    if ( (result = (void**)malloc((size_t)(data_size + pointer_size))) == NULL ) {
            return NULL;
    }

    // take the first bit for a vector pointing to the m_pData for each row
    char* pdata = (char*)result + pointer_size;
    if ((unsigned long)pdata % size) {
      pdata += size - (unsigned long)pdata % size;
    }

    // for each row, set up the pointer to its m_pData
    for (i = 0; i < rows; i++) {
            result[i] = (void*)pdata;
            pdata += row_size;
    }

    return result;
}

然后,我將使用以下命令設置矩陣:

char** buffer = (char**)matrix2D(height, width, sizeof(char));

我將使用以下方法初始化數組:

for (int i = 0; i < height; ++i)
    for (int j = 0; j < width; ++j)
        buffer[i][j] = ' ';

我將使用以下命令打印數組:

for (int i = 0; i < height; ++i) {
    for (int j = 0; j < width; ++j)
        cout << buffer[i][j];
    cout << endl;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM