8 years, 3 months ago.

std::vector<bool> reads the last bit as zero after an vector::insert has been performed

Hi all, I have been trying to write a code to do bit-stuffing of a sequence of bits, which is used to avoid misreading of data with a flag-pattern. The flag is at the start of the sequence, flag = 01111110. vector::insert is used to insert a 0 bit whenever five continuous 1s appear in the data. The problem is, once an insert operation is performed, the last bit is always read as zero. The same is not true when the code is run on my laptop. So, I think it's a bug in the library (#include "vector"). The code is given below,


#include "vector"
    void bitStuff(std::vector<bool>& binInput){    
        // state transition
        int state = 0; //Initial state
        // mealy machine
        std::vector<bool>::iterator iter;
//        iters become void after insertion
        int count(8);
        //ignore the flag here : size 8
        for(iter = binInput.begin() + 8 ; iter != binInput.end() ; ++iter){
            // if input is 1 ...
                case 0:
                    state = 1;
                case 1:
                    state = 2;
                case 2:
                    state = 3;
                case 3:
                    state = 4;
                case 4:
                    // inserts a single bit
                    binInput.insert(iter+1, false);
                    state = 0;
//                    iters become void after insertion
                    iter = binInput.begin() + count;
            // if input is 0 ...
                state = 0;

sample output : case 1: input : 000000001111001, output : 000000001111001, case 2: input : 00000000111111111111001, output : 0000000011111011111011000. As can be seen the last bit of the sequence after insertion operation is zero.

Any help is appreciated.. Thank you...

It would be weird if they have an error in vector, although if the same does work different on your pc I guess it is possible.

However reason for comment: In general using vector for just some bit manipulation is enormous overkill and consumes tons of resources compared to just doing it yourself directly.

posted by Erik - 04 Feb 2015

Hi Erik, thank you very much for your response. What exactly do you mean by doing it directly ? I found vector<bool> useful over an array of chars for the following reasons, (i)vector<bool> is supposed to be optimised for space, i.e instead of storing a vector of bools, each entry is a bit, (ii)ease of insertion, (iii) the size of the vector may not be a multiple of 8. Please correct me if I'm wrong. I'm new to mbed and c++. Is there any other way to achieve the same ? Thank you...

posted by Shreesha S 05 Feb 2015
Be the first to answer this question.