Frogical
Frogical

Reputation: 185

Is it possible to rewrite my code using STL algorithms?

I have a nested loop and I am hoping to rewrite it using STL algorithms. Can someone help me out?

std::bitset<array_size * 8> bitset {};
short bitsetIndex {0};
for (int i = 0; i < array_size; ++i) {
    std::bitset<8> cBitset { (unsigned char) charArray[i] };
    for (int i = 0; i < cBitset.size(); ++i) {
        if(cBitset.test(i)) {
            bitset.set(bitsetIndex);
        }
        bitsetIndex++;
    }
}
return bitset;

Upvotes: 0

Views: 161

Answers (1)

Evg
Evg

Reputation: 26282

It looks like you want to represent charArray as a collection of bits. A simple loop and a couple of bit operations will do the job:

using Bitset = std::bitset<array_size * 8>;
Bitset bitset;
for (auto i = array_size; i > 0; --i) {
    bitset <<= 8;
    bitset |= Bitset(static_cast<unsigned char>(charArray[i - 1]));
}
return bitset;

Depending on what charArray is, the loop could also be rewritten with iterators:

using Bitset = std::bitset<array_size * 8>;
Bitset bitset;
for (auto it = std::rbegin(charArray); it != std::rend(charArray); ++it) {
    bitset <<= 8;
    bitset |= Bitset(static_cast<unsigned char>(*it));
}
return bitset;

Finally, if you really want to use some standard library algorithm, you can use std::accumulate:

using Bitset = std::bitset<array_size * 8>;
return std::accumulate(std::rbegin(charArray), std::rend(charArray), Bitset{}, 
    [](Bitset bs, auto ch) { return (bs << 8) | 
        std::bitset<array_size * 8>(static_cast<unsigned char>(ch));
});

Demo

Upvotes: 1

Related Questions