简体   繁体   中英

Vectorize on array of bool in c++

I have an array of bool (or any equivalent structure). I need to count the number of true between the nth and mth position. Is it possible to get the compiler to vectorize this so that 64 or more elements are checked in one go?

That already happens if you compile with -O3 and potentially -march=native :

#include <algorithm>
#include <iostream>

void count(char* v) {
    auto x = std::count(&v[0], &v[100], true);
    std::cout << x << std::endl;
}

With gcc, this gives you a bunch of vp* instructions, which means that the count is vectorized. You can easily check this on godbolt .

There actually is a speciation of std::vector for bool : std::vector<bool> but it's not great and doesn't have a count function.

Instead you could consider using std:: bitset , that does offer a count member function. It's more or less designed for the purpose and will likely have an efficient implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM