On 05.05.2012 17:17, David Kevin wrote:
> Hi,
> I would be grateful if somebody could explain why following code
> causes assertions failures:
Because it's wrong.
> //#include "stdafx.h" //neccessary if you compile with VC++ 2008
No, it's not necessary. Just turn off use of precompiled headers in the
settings.
> #include<iostream>
> #include<cstdlib>
> #include<ctime>
Just to avoid some possible grief, better use the ".h" versions of the
above headers.
> #include<vector>
> #include "stdio.h"
> using namespace std;
>
> class A {
> public:
> A() {}
> A(int currentDepth, int depth) { cout<< currentDepth<< " "<< depth
> << "\n"; }
> vector<A>* vecA;
Uh, oh, a pointer to a vector. Which isn't even initialized. And which
is a public data member.
You can't get it much wronger than that.
This code is doomed.
> };
>
> vector<A> recursion(int fixedDepth) {
> fixedDepth--;
> getchar();
What's that for?
> cout<< "We are on level: "<< fixedDepth<< "\n";
> vector<A> vecA;
> int Max=rand() % 5+1;
Use 'const' where you can.
> for(int i=0; i<Max; i++) {
> A a;
> vecA.push_back(a);
> }
> vector<A>::iterator it;
> for(it=vecA.begin(); it!=vecA.end(); it++) {
> if(fixedDepth==0) {
> if(it==vecA.end()) break;
> it++;
> continue;
> }
> it->vecA=new vector<A>;
The above doesn't do anything, really. Except use time and invoke
possible side effects.
> *it->vecA=
Here you have a problem.
I have already told you what it is.
What is it?
> recursion(fixedDepth);
Here you have another problem - can you guess what it is?
> }
> return vecA;
> };
>
> int main()
> {
> srand((unsigned)time(0));
> vector<A> a=recursion(2);
> return 0;
> }
>
> It is interesting that if one doesn't use random numbers but in for
> loop there is single, known before run-time number instead of MAX it
> seems to work nicely. My compiler is Visual C++ 2008.
Hm.
Cheers & hth.,
- Alf
|