当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - 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

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: