Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ OpenMP and std::vector<bool>

Why does the following code not work (as excpected) for std::vector of bool ? Some elements are randomly false in the bool-vector. For the int vector all works fine (tested with many more than just 3 loops).

I am on ubuntu 14.04 64bit with g++ 4.8.4.

#include <iostream>
#include <vector>

using namespace std;


class TestBool
{
public:
    TestBool() {}
    bool test() {return true;}
    int testInt() {return 10;}
};
void testBVec(vector<bool> &bv, size_t loop)
{
    cout << "boolvec loop " << loop << endl;
    for(size_t i = 0; i < bv.size(); i++) {
        if( ! bv[i])
            cout << "wholy shit with bool at index " << i << endl;
    }
}
void testIntVec(vector<int> &iv, size_t loop)
{
    cout << "intVec loop " << loop << endl;
    for(size_t i = 0; i < iv.size(); i++) {
        if( iv[i] != 10)
            cout << "wholy shit with int at index " << i << endl;
    }
}


int main()
{
    vector<TestBool> tv(10);
    size_t loops = 3;

    for(size_t i = 0; i < loops; i++ ) {
        vector<bool> bv(10);
        vector<int> iv(10);

        #pragma omp parallel for
        for(int j = 0; j < 10; ++j) {
            bv[j] = tv[j].test();
            iv[j] = tv[j].testInt();
        }
        testBVec(bv, i+1);
        testIntVec(iv, i+1);
    }

    return 0;
}
like image 251
Mr. B0ne Avatar asked Aug 19 '16 10:08

Mr. B0ne


Video Answer


1 Answers

Most probably it's because vector<bool> transformed to array of bits by compiler. Just use vector<int> or vector<char> storing 0s and 1s into it, if you don't need bit array.

like image 58
Anton Malyshev Avatar answered Sep 29 '22 17:09

Anton Malyshev