Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
2.0 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //
  7. //=============================================================================//
  8. #include <windows.h>
  9. #include <stdio.h>
  10. template <class T, int nBlockSize, int nMaxBlocks>
  11. class BlockArray
  12. {
  13. public:
  14. BlockArray()
  15. {
  16. nCount = nBlocks = 0;
  17. }
  18. ~BlockArray()
  19. {
  20. GetBlocks(0);
  21. }
  22. T& operator[] (int iIndex);
  23. void SetCount(int nObjects);
  24. int GetCount() { return nCount; }
  25. private:
  26. T * Blocks[nMaxBlocks+1];
  27. short nCount;
  28. short nBlocks;
  29. void GetBlocks(int nNewBlocks);
  30. };
  31. /*
  32. template <class T, int nBlockSize, int nMaxBlocks>
  33. BlockArray<T,BlockSize,nMaxBlocks>::BlockArray()
  34. {
  35. nCount = nBlocks = 0;
  36. }
  37. template <class T, int nBlockSize, int nMaxBlocks>
  38. BlockArray<T,BlockSize,nMaxBlocks>::~BlockArray()
  39. {
  40. GetBlocks(0); // free blocks
  41. }
  42. */
  43. template <class T, int nBlockSize, int nMaxBlocks>
  44. void BlockArray<T,nBlockSize,nMaxBlocks>::
  45. GetBlocks(int nNewBlocks)
  46. {
  47. for(int i = nBlocks; i < nNewBlocks; i++)
  48. {
  49. Blocks[i] = new T[nBlockSize];
  50. }
  51. for(i = nNewBlocks; i < nBlocks; i++)
  52. {
  53. delete[] Blocks[i];
  54. }
  55. nBlocks = nNewBlocks;
  56. }
  57. template <class T, int nBlockSize, int nMaxBlocks>
  58. void BlockArray<T,nBlockSize,nMaxBlocks>::
  59. SetCount(int nObjects)
  60. {
  61. if(nObjects == nCount)
  62. return;
  63. // find the number of blocks required by nObjects
  64. int nNewBlocks = (nObjects / nBlockSize) + 1;
  65. if(nNewBlocks != nBlocks)
  66. GetBlocks(nNewBlocks);
  67. nCount = nObjects;
  68. }
  69. template <class T, int nBlockSize, int nMaxBlocks>
  70. T& BlockArray<T,nBlockSize,nMaxBlocks>::operator[] (int iIndex)
  71. {
  72. if(iIndex >= nCount)
  73. SetCount(iIndex+1);
  74. return Blocks[iIndex / nBlockSize][iIndex % nBlockSize];
  75. }
  76. typedef struct
  77. {
  78. char Name[128];
  79. int iValue;
  80. } Buffy;
  81. void main(void)
  82. {
  83. BlockArray<Buffy, 16, 16> Buffies;
  84. for(int i = 0; i < 256; i++)
  85. {
  86. Buffies[i].iValue = i;
  87. strcpy(Buffies[i].Name, "Buk bUk buK");
  88. }
  89. for(i = 0; i < 256; i++)
  90. {
  91. printf("%d: %s\n", Buffies[i].iValue, Buffies[i].Name);
  92. }
  93. Buffies.SetCount(10);
  94. }