正确实现二维向量填充

时间:2019-03-16 02:16:19

标签: c++ vector constructor

我在实现文件中有一个构造函数和一个方法:

Boggle::Boggle(std::string boardString){

dim = sqrt(boardString.size());
vector<vector<char> > grid(dim, vector<char>(dim));
int co = 0;
for (int i = 0; i < dim; i++)
{
    for (int j = 0; j < dim; j++)
    {
        grid[i][j] = boardString[co];
        co++;
    }    
}
}

void Boggle::printMe() {

for (auto inner : grid)
{
    for (auto item : inner)
    {
        cout << item << " ";
    }
    cout << endl;
}
}

该程序执行,但不执行任何操作。如您所见,我在声明矢量时已调整其大小。我认为问题在于我的逻辑,也许是从字符串向矢量分配一个字符。

1 个答案:

答案 0 :(得分:0)

正如注释中所暗示的,向量grid对于您的函数而言是本地的。您很可能想使用类变量,但最终创建了一个局部变量。您可以使用resize设置网格的尺寸。最好ceil sqrt,以确保我们不丢失任何字符。

示例:

#include <stdio.h>
#include <vector>
#include <string>
#include <cmath>
#include <iostream>

using namespace std; // Avoid this

class Boggle{

    public:
    int dim;
    vector<vector<char>> grid;

    Boggle(string boardString);
    void printMe();

};


Boggle::Boggle (std::string boardString)
{

  dim = ceil(sqrt(boardString.size ()));
  grid.resize(dim, vector <char>(dim));
  int co = 0;
  for (int i = 0; i < dim; i++) {
    for (int j = 0; j < dim; j++)
    {
      grid[i][j] = boardString[co];
      co++;
    }
  }
}

void Boggle::printMe ()
{

    for (auto inner:grid) {

        for (auto item:inner)
        {
          cout << item << " ";
        }

        cout << endl;
    }
}

int main(){

    Boggle boggle("hello world");

    boggle.printMe();

    return 0;
}


结果:
h e l l

o w o

r l d