fork download
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. int main()
  5. {
  6. const int LOOPS = 100;
  7.  
  8. std::vector<int> myVector;
  9. int reallocations = 0;
  10.  
  11. for(int i = 0; i < LOOPS; ++i)
  12. {
  13. size_t oldCapacity = myVector.capacity();
  14.  
  15. myVector.push_back(i);
  16.  
  17. size_t newCapacity = myVector.capacity();
  18.  
  19. if(oldCapacity != newCapacity)
  20. {
  21. ++reallocations;
  22. float percentageGrowth = (float(newCapacity - oldCapacity) / float(oldCapacity)) * 100.0f;
  23.  
  24. std::cout << "Reallocation occured on pushing element " << (i+1) << ".\n"
  25. << "Old capacity: " << oldCapacity << "\n"
  26. << "New capacity: " << newCapacity << " (" << percentageGrowth << "% growth)\n" << std::endl;
  27. }
  28. }
  29.  
  30. std::cout << "\n--------------------------------------------------\n"
  31. << "Total reallocations over " << LOOPS << " elements: " << reallocations << std::endl;
  32.  
  33. return 0;
  34. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
Reallocation occured on pushing element 1.
Old capacity: 0
New capacity: 1 (inf% growth)

Reallocation occured on pushing element 2.
Old capacity: 1
New capacity: 2 (100% growth)

Reallocation occured on pushing element 3.
Old capacity: 2
New capacity: 4 (100% growth)

Reallocation occured on pushing element 5.
Old capacity: 4
New capacity: 8 (100% growth)

Reallocation occured on pushing element 9.
Old capacity: 8
New capacity: 16 (100% growth)

Reallocation occured on pushing element 17.
Old capacity: 16
New capacity: 32 (100% growth)

Reallocation occured on pushing element 33.
Old capacity: 32
New capacity: 64 (100% growth)

Reallocation occured on pushing element 65.
Old capacity: 64
New capacity: 128 (100% growth)


--------------------------------------------------
Total reallocations over 100 elements: 8