Akash
Akash

Reputation: 1726

Why are my vector<int>s not defaulting to 0?

The below code works fine on ideone, gives an output of

10000
10000

as expected

However on my local machine, the output is of the sort

9990
9998

All the code does is create a vector of 10k int's and count the number of 0's in it. Once using a class, and once in main.

If I run the code locally in debug mode, it results in

0
0

I'm using codeBlocks on Windows 7 with the default GNU GCC Compiler (though it compiles C++, so I guess its different than the Linux GCC which does only C)

#include<iostream>
#include<vector>
using namespace std;
class vecttest
{
    vector<int> vect;
    public:
    vecttest()
    {
        vect.reserve(10000);
    }
    int zcount()
    {
        int count=0;
        for(int i=0;i<10000;i++)
        {
            if(vect[i]==0)
                count++;
        }
        return count;
    }
};
int main()
{
    vecttest v;
    cout<<v.zcount();

    vector<int> v2;
    v2.reserve(10000);
    int count=0;
        for(int i=0;i<10000;i++)
        {
            if(v2[i]==0)
                count++;
        }
    cout<<endl<<count;
}

ideone link: http://ideone.com/q1XRvQ

Upvotes: 0

Views: 106

Answers (1)

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

The method reserve(..) only guarantees that the space is allocated. It does not guarantee the values in the elements of the vector. The only thing that will happen is that your counting will not crash. The resulting value is implementation/allocation/etc dependent.

The core idea that is necessary to understand about containers and iterators is that they are the same insecure as simple arrays:

char b1[100];
vector<char> b2(100);

void f()
{
   char c1 = b1[200];
   char c2 = b2[300];
}

In both cases compiler will generate code that will pick up something outside of the array. Both examples trigger undefined behavior. Maybe the code will crash, maybe not. Both accesses are equally bad.

The main reason for such design is speed. Access to array should be fast. This is core idea of C/C++. The value of the index is the responsibility of the programmer. Compiler will not check. Like it or not, this is so.

Upvotes: 2

Related Questions