fork download
  1. #include <vector>
  2. #include <memory> // for auto_ptr
  3. #include <cmath> // for the log10 and floor functions
  4. #include <iostream>
  5. #include <iomanip> // for the setw function
  6.  
  7. using namespace std;
  8.  
  9. typedef vector< int > IntRow;
  10. typedef vector< IntRow > IntTable;
  11.  
  12. auto_ptr< IntTable > getZigZagArray( int dimension )
  13. {
  14. auto_ptr< IntTable > zigZagArrayPtr( new IntTable(
  15. dimension, IntRow( dimension ) ) );
  16.  
  17. // fill along diagonal stripes (oriented as "/")
  18. int lastValue = dimension * dimension - 1;
  19. int currDiag = 0;
  20. int loopFrom;
  21. int loopTo;
  22. int i;
  23. int row;
  24. int col;
  25. do
  26. {
  27. if ( currDiag < dimension ) // if doing the upper-left triangular half
  28. {
  29. loopFrom = 0;
  30. loopTo = currDiag;
  31. }
  32. else // doing the bottom-right triangular half
  33. {
  34. loopFrom = currDiag - dimension + 1;
  35. loopTo = dimension - 1;
  36. }
  37.  
  38. for ( i = loopFrom; i <= loopTo; i++ )
  39. {
  40. if ( currDiag % 2 == 0 ) // want to fill upwards
  41. {
  42. row = loopTo - i + loopFrom;
  43. col = i;
  44. }
  45. else // want to fill downwards
  46. {
  47. row = i;
  48. col = loopTo - i + loopFrom;
  49. }
  50.  
  51. ( *zigZagArrayPtr )[ row ][ col ] = currNum++;
  52. }
  53.  
  54. currDiag++;
  55. }
  56. while ( currDiag <= lastValue );
  57.  
  58. return zigZagArrayPtr;
  59. }
  60.  
  61. void printZigZagArray( const auto_ptr< IntTable >& zigZagArrayPtr )
  62. {
  63. size_t dimension = zigZagArrayPtr->size();
  64.  
  65. int fieldWidth = static_cast< int >( floor( log10(
  66. static_cast< double >( dimension * dimension - 1 ) ) ) ) + 2;
  67.  
  68. size_t col;
  69. for ( size_t row = 0; row < dimension; row++ )
  70. {
  71. for ( col = 0; col < dimension; col++ )
  72. cout << setw( fieldWidth ) << ( *zigZagArrayPtr )[ row ][ col ];
  73. cout << endl;
  74. }
  75. }
  76.  
  77. int main()
  78. {
  79. printZigZagArray( getZigZagArray( 5 ) );
  80. }
Compilation error #stdin compilation error #stdout 0s 3096KB
stdin
Standard input is empty
compilation info
prog.cpp: In function 'std::auto_ptr<std::vector<std::vector<int> > > getZigZagArray(int)':
prog.cpp:14:37: warning: 'auto_ptr' is deprecated (declared at /usr/include/c++/4.9/backward/auto_ptr.h:87) [-Wdeprecated-declarations]
  auto_ptr< IntTable > zigZagArrayPtr( new IntTable(
                                     ^
prog.cpp:51:40: error: 'currNum' was not declared in this scope
    ( *zigZagArrayPtr )[ row ][ col ] = currNum++;
                                        ^
prog.cpp: At global scope:
prog.cpp:61:67: warning: 'auto_ptr' is deprecated [-Wdeprecated-declarations]
 void printZigZagArray( const auto_ptr< IntTable >& zigZagArrayPtr )
                                                                   ^
stdout
Standard output is empty