1

The code is as follows.

int main()
{
    map<int,int> a;
    for (int i = 0; i < 6; i++)
    {
        a.insert(make_pair(i, i+1));
    }
    
    map<int,int>::iterator it;
#pragma omp parallel for default(none) shared(a)
    for (it = a.begin(); it != a.end(); it++)
    {
        printf("the first is %d\n", it->first);
    }
    return 0;
}

the code compilation fails. But I can use vector iterator, the code is as follows:

    int main()
    {
            vector<int> vec(23,1);
            vector<int>::iterator it;
            // map<int,int>::iterator it;
#pragma omp parallel for default(none) shared(vec)
            for (it = vec.begin(); it < vec.end(); it++)
            {
                printf("the number is %d\n", *it);
            }
        return 0;
    }

the vector iterator can work correctly.How can I parallelize for loop with map iterator directly as the same way of using vector iterator? The newest OpenMP version (5.2) has been published, OpenMP website. Can I do this by the newest OpenMP API?

2
  • 1
    Can you include the compiler error? Commented Dec 15, 2021 at 2:46
  • Why not store your map iterators in a vector, and then loop with that? Commented Dec 15, 2021 at 3:12

1 Answer 1

3

The iterator for a std::map is not a random-access-iterator, so it cannot be used as the control variable in an OpenMP parallel for loop. The iterator for a std::vector is a random access iterator, so it can be used.

The random access is necessary so that the OpenMP runtime can quickly advance the loop counter for each thread to its proper initial value (and the later iteration values it will compute for that thread).

Sign up to request clarification or add additional context in comments.

2 Comments

I compiled both of these versions and none of them was parallelized.
As remarked above: please include the actual error message. The std::vector loop should parallelize just fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.