Search code examples
parallel-processingopenmp

How to traverse two-dimensional vector by OpenMP


I'm new to OpenMP and got an error that I can't fix.

Suppose I have a two-dimensional vector:

vector<vector<int>> a{{...}, {...}, ...};

I want to traverse it as

#pragma omp parallel for collapse(2)
for (int i = 0; i < a.size(); i++){
    for (int j = 0; j < a[i].size(); j++){
        work(a[i][j]);
    }
}

However, there is an error: condition expression refers to iteration variable ‘i’.

So how can I traverse the two-dimensional vector correctly?


Solution

  • The problem is that the end condition of second loop depends on the first loop's index variable (a[i].size()). Only OpenMP 5.0 (or above) supports so-called non-rectangular collapsed loops, so if you use earlier OpenMP version you cannot use the collapse(2) clause here. Just remove collapse(2) clause and it will work.

    Note that, if a[i].size() is the same for all i, then you can easily remove this dependency.