【问题标题】:3D Array to 3D std::vector3D 数组到 3D std::vector
【发布时间】:2013-08-21 17:13:43
【问题描述】:

我在我的代码函数中用 3D std::vector 替换了 3D 数组,它进入了一个无限循环。你能给我一个提示吗,我真的需要使用向量而不是数组。谢谢:)
我的初始代码是:

//arr is a 3D array of a sudoku table,the 3 rd dimension is for keeping values 0 to 13  
//for a cell, and when I assign values I start from index 1 to 12

bool sol(int arr[12][12][13]) {
int row,col;

if(!find_empty(arr,row,col)) return true;

for(int i=1;i< 12;i++) { //for digits 1 to 12
    if(is_working(arr,row,col,arr[row][col][i]) ) {   //if i can put the value in a cell
        arr[row][col][0] = arr[row][col][i];  //replace the first element for a cell with that value
     //here I want to use vector because I want to use an ac3 algorithm 
     //and remove those values that not satisfy constraints and shrink domain size having less values to verify with backtrack

        if(sol(arr)) return true;

        arr[row][col][0] = 0;
    }
}

return false;//if not backtrack
}

我将 arr 替换为:

std::vector<std::vector<std::vector<int> > > vec;
vec.resize(12);
for(int i=0;i<12;i++)
{
vec[i].resize(12);
for(int j=0;j<12;j++)
{
    vec[i][j].resize(13);
    for(int k=0;k<13;k++)
        vec[i][j][k]=table[i][j][k];
   }
} 


bool sol(std::vector<std::vector<std::vector<int> > >& vec) {
int row,col;

if(!find_empty(vec,row,col)) return true;

for(int i=1;i< vec[row][col].size();i++) {//for remainig values in domain
    if(is_working(vec,row,col,vec[row][col][i]) ) {//same as above but having less values to verify for
        vec[row][col][0] = vec[row][col][i];

        if(sol(vec)) return true;

        vec[row][col][0] = 0;
    }
}

return false;
}

现在它进入了一个无限循环!初始代码没有错误,这是一个简单的回溯。我将arr替换为vec后出现问题。你能给关于如何用 3D 矢量替换 3D arr 的一些建议

【问题讨论】:

  • “编译时的无限循环” ehmmm 这是什么意思?
  • 您确定要使用索引1 开始循环吗?
  • vector::resize 通过插入或删除元素来更改矢量的实际内容
  • 您是否尝试过调试并查看发生无限循环的位置?
  • 是的,它出现在 for 中

标签: c++ arrays vector


【解决方案1】:

你的问题不够清楚。如果您还可以发布 is_working 和 find_empty 的代码,那么我们将能够看到您如何获取行和列的值。 我会将此作为评论,但作为新成员并且没有足够的声誉,我必须将此作为答案。一旦你分享了 is_working() 和 find_empty() 的代码,我会编辑它

【讨论】:

  • 问题不在代码中。问题出在数据结构上,3D 向量不知何故没有修改他的元素,导致算法不一致
  • 一定是代码有问题,或者你设置向量值的方式有问题。但我很高兴你让它以一种或另一种方式工作。
【解决方案2】:

我已经解决了这个问题。我使用了向量矩阵而不是 3D 向量,效果很好:D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 2022-11-13
    • 2012-12-09
    • 1970-01-01
    相关资源
    最近更新 更多