Advertisement
SilverTES

Simple Re-sizable vector of pointers

Jan 30th, 2017
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. template <class M = std::string, class E = int>
  5. E log(M msg, E error = 0)
  6. {
  7.     std::cout << msg;
  8.     return error;
  9. }
  10.  
  11. struct Cell
  12. {
  13.     int index;
  14. };
  15.  
  16. std::vector<Cell*> vecInt;
  17.  
  18.  
  19. void showVec()
  20. {
  21.     log("\n Vec = ");
  22.     for (auto & it: vecInt)
  23.     {
  24.         std::cout << "[ " << it->index << " ]";
  25.     }
  26. }
  27.  
  28. void resizeVec(unsigned newSize)
  29. {
  30.     if (newSize < vecInt.size())
  31.     {
  32.         for (int i=0; i < newSize - 1; ++i)
  33.         {
  34.             delete vecInt.back();
  35.             vecInt.pop_back();
  36.         }
  37.  
  38.         vecInt.resize(newSize);
  39.     }
  40.     else if (newSize > vecInt.size())
  41.     {
  42.         vecInt.resize(newSize, new Cell{0});
  43.     }
  44.     else if (newSize == vecInt.size())
  45.     {
  46.         log ("\n Nothing to resize !\n");
  47.     }
  48.  
  49. }
  50.  
  51.  
  52. int main()
  53. {
  54.  
  55.     for (int i=0; i<5; ++i)
  56.     {
  57.         vecInt.push_back(new Cell{i});
  58.     }
  59.  
  60.     showVec();
  61.     resizeVec(7);
  62.     showVec();
  63.     resizeVec(4);
  64.     showVec();
  65.  
  66.     resizeVec(4);
  67.     showVec();
  68.  
  69.     return log("\n--- End of Main ---\n");
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement