std::experi...al::popcount(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

πŸ’… NAME πŸ’…

std::experimental::popcount β€” okay so it's literally std::experimental::popcount, bestie, that's the whole name 😭✨

This page lives in the C++ Standard Libary (yes that's how it's spelled on the page, iykyk, we don't fix it, we respect it 🫢), serving up std::experi...al::popcount(3) realness.


✨ Synopsis ✨

First things first, it's defined in the header <experimental/simd> β€” write that down, queen πŸ‘‘

template< class T, class Abi >                        (parallelism TS v2)
int popcount( const simd_mask<T, Abi>& k ) noexcept;

So what does it actually do? It returns the number of true values in the mask k. That's it. That's the whole vibe check πŸ’… Count the trues, hand back a number, no drama.

Note the noexcept β€” it's giving calm, unbothered, cannot be shaken 🌸


πŸŽ€ Parameters πŸŽ€

  • k β€” the simd_mask to apply the reduction to. That's the icon right there, the main character, the thing you're counting the trues in πŸ‘‘

⭐ Return value ⭐

An int in the range [0, simd_size_v<T, Abi>). So lowkey it can be zero, highkey it can't reach simd_size_v<T, Abi> β€” that upper bound is excluded, fr fr πŸ™ˆ


πŸ”₯ Example πŸ”₯

Run this code, bestie, it eats:

#include <cstddef>
#include <experimental/simd>
#include <iostream>
namespace stdx = std::experimental;

template<typename Abi>
int count_zeros(stdx::simd<int, Abi> v)
{
    return stdx::popcount(v == 0); // v == 0 returns a simd_mask
}

void println(auto rem, auto const v)
{
    std::cout << rem << ": ";
    for (std::size_t i = 0; i != v.size(); ++i)
        std::cout << v[i] << ' ';
}

int main()
{
    stdx::simd<int> x{8};
    println("x", x);
    std::cout << "  zeros: " << count_zeros(x) << '\n';

    x[3] = x[1] = false;
    println("x", x);
    std::cout << "  zeros: " << count_zeros(x) << '\n';
}

Notice the little comment doing the explaining: // v == 0 returns a simd_mask β€” the way that comparison just drops a mask in your lap and popcount scoops it up 🧚 Obsessed.


🌈 Possible output 🌈

x: 8 8 8 8   zeros: 0
x: 8 0 8 0   zeros: 2

First line: zero zeros, absolute slay. Second line: we set x[3] = x[1] = false, and boom, two zeros materialise. The math is mathing πŸ’€βœ¨


Heads up bestie: it says Possible output, so don't come for me if your terminal prints something slightly different β€” it's possible, not a promise 🫢

And that's the whole page, no cap! Signing off with the receipts: this one's from http://cppreference.com, version 2024.06.10, filed under std::experi...al::popcount(3) πŸŽ€πŸ¦‹ See you in the next manpage, mwah πŸ’–

πŸ“¦ where this page comes from