In the above function, I create a static array. How can it be reset once when entering the function for the first time?

typedef unsigned char uchar; typedef unsigned long long int ullong; // Π Π΅ΠΊΡƒΡ€Π΅Π½Ρ‚Π½Ρ‹ΠΉ Π°Π»Π³ΠΎΡ€ΠΈΡ‚ΠΌ нахоТдСния F(n) // F(n) - число Π€ΠΈΠ±ΠΎΠ½Π°Ρ‡ΠΈ, n - порядковый Π½ΠΎΠΌΠ΅Ρ€ ullong Fibonachi_Recursion_With_Memory(const uchar &_n) { static ullong *const M = new ullong[_n + 1]; // ДинамичСски Π²Ρ‹Π΄Π΅Π»Π΅Π½Ρ‹ΠΉ массив (ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ Π½ΡƒΠΆΠ½ΠΎ ΠΎΠ±Π½ΡƒΠ»ΠΈΡ‚ΡŒ) ////////////////////////////////////////////////////////////////////// - (ΠΌΠΎΠΉ способ) static bool emptyVector(false); if(!emptyVector) { for(uchar i = 0; i <= _n; i++) M[i] = 0; emptyVector = true; } ////////////////////////////////////////////////////////////////////// if(_n <= 2) return 1; if(M[_n] != 0) return M[_n]; return M[_n] = Fibonachi_Recursion_With_Memory(_n - 1) + Fibonachi_Recursion_With_Memory(_n - 2); } 
  • one
    I did not understand your code. After all, if you call your code 2 times, for example Fibonachi_Recursion_With_Memory(1); Fibonachi_Recursion_With_Memory(5); Fibonachi_Recursion_With_Memory(1); Fibonachi_Recursion_With_Memory(5); it will be nonsense, because the array in the second case will be 1 element in size. - zenden2k
  • @ zenden2k, opa, lost, thanks for the amendment) - neitron

2 answers 2

Easy!

 static ullong *const M = new ullong[_n + 1](); 

Will work in C ++ 03

If your compiler supports C ++ 2011, then you can just write

 static ullong *const M = new ullong[_n + 1] {}; 

Otherwise, you can write a separate function to initialize this array. For example,

 inline ullong * init( uchar n ) { ullong *p = new ullong[n]; std::memset( p, 0, n * sizeof( ullong ) ); return p; } 

and

 static ullong *const M = init( _n + 1 ); 

Or, again, if the compiler supports, you can use the lambda expression declared inside the function before declaring a static variable. for example

 auto l = []( uchar n ) -> ullong * { int *p = new ullong[n]; return ( ullong * )std::memset( p, 0, n * sizeof( ullong ) ); }; static ullong *const M = l( _n + 1 ); 

And do not use identifiers that begin with an underscore or end with an underscore, as well as identifiers consisting of one capital letter. This is a bad programming style.