Home > Mobile >  Generic set insert function int
Generic set insert function int

Time:04-27

I have a little problem with the next task. The insert function should also work for the int type but unfortunately it doesn't work. What might be the problem?

Some example for the insert function call:

Set<int, 4> s0;

s0.insert(2);

This is an four-elemet array and the firs element is 2.

template <class T, size_t n = 10>
class Set{
private:
    T adat[n];
public:
    size_t size (){return n;}
    bool isElement (T num){
        for (size_t i = 0; i < n; i  )
        {
            if (adat[i] == num)
                return true;
        }
        return false;
    }
    void insert (T data){
        if (!isElement(data)){
            size_t i = 0;
            while((adat[i] != 0)||(i != n))
                i  ;
            if (i != n)
            {
                adat[i] = data;
            }
            else
                throw("The array is full!");
        }
    }
};

CodePudding user response:

This is a maybe somehow subtle out of bounds bug. Cool.

In this while loop

while((adat[i] != 0)||(i != n))
   i  ;

you will go out of bounds, because the last element is "(n-1)" and not "n". And you will always go out of bounds, because of the "or" in the condition. The loop will always run at least until "i==n", because of the right part of the "or". And then, after being out of bounds, the accessed value "adat[i]" will be indetermined, and most likely not null. So, you safeguard "i!=n" will never be touched.

This also because of boolean shortcut evaluation. if "(adat[i] != 0)" is already true, then the next term in the "or" has no meaning and will also be not evaluated.

And then the endless loop will run forever . . .

You must also initialize your "adat" array, to be sure that it contains default values.

Do this with: T adat[n]{};.

Finally, to fix your while loop, please write:

while ((adat[i] != 0) && (i < n)) {
  • Related