-2

I replaced a 3D array with a 3D std::vector in my code function and it's entering a infinite loop at compiling.If I had used a 3D array arr[ ][ ][ ] it would work perfect.Could you give me a hint,I really need to use a vector instead an array.Thanks:)

My initial code was:

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

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

    for(int i=1;i< arr[row][col].size();i++) {
        if(is_working(arr,row,col,arr[row][col][i]) ) {
            arr[row][col][0] = arr[row][col][i];

            if(sol(arr)) return true;

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

    return false;
}

I replace arr with

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];
    }
}

and now it's entering a infinite loop!The initial code has no errors,it's a simple backtracking.The problem appears after I replace arr with vec.Could you give me some advice.Sorry for the first posting!

4
  • 1
    "Could you guys please help me." No, not if you don't help us by making your code readable. Commented Aug 21, 2013 at 16:21
  • 1
    You should pass your vector by (const?) reference or it will copy the entire vector. If you want to modify the vector outside the function, this is actually required. Commented Aug 21, 2013 at 16:42
  • 2
    Yay now there are more magic numbers! Also, please don't edit your question so dramatically after answers are posted. You likely now need a new question. Your segfault is fixed, accept an answer, answer your own original question, or close this question and ask a separate question. Commented Aug 21, 2013 at 16:53
  • I know it's a duplicate because I could could not delete it Commented Aug 22, 2013 at 16:41

1 Answer 1

3
for(int i=1;i<=vec[row][col].size();i++)

should be

for(int i=1;i<vec[row][col].size();i++)

and unless you want to skip the first item in the vector you probably REALLY intend this:

for(int i=0;i<vec[row][col].size();i++)

and you could also consider using iterators, which make your code more flexible

for(auto it = vec[row][col].begin(); it != vec[row][col].end(); it++)

Also a style point, you reference vec[row][col] a lot within the same bit of code. It helps readability to do something like this:

vector<someType>& tempVector = vec[row][col];

And then spread that reference throughout your code instead.

ALSO, and potentially most importantly:

k++;//Where on earth did you declare/define k and what else is it doing?????????
return false;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.