fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <array>
  4. using namespace std;
  5.  
  6. int main()
  7. {
  8. std::vector<int> vec100(100); // a vector of 100 ints
  9. std::vector<int> vec2(2); // a vector of 2 ints
  10. std::array<int,100> arr100; // an array of 100 ints
  11. std::array<int,2> arr2; // an array of 2 ints
  12.  
  13. // notice how the number of elements does not change the size
  14. // of the vector itself:
  15. cout << "sizeof vec100 = " << sizeof(vec100) << endl;
  16. cout << "sizeof vec2 = " << sizeof(vec2) << endl;
  17.  
  18. // This is because the vector does not contain the elements, but rather
  19. // it contains a pointer to them. This means to access the elements,
  20. // it has to dereference that pointer, which means an extra memory access
  21.  
  22.  
  23. // On the other hand... notice how the number of elements does
  24. // change the size of an array:
  25. cout << "sizeof arr100 = " << sizeof(arr100) << endl;
  26. cout << "sizeof arr2 = " << sizeof(arr2) << endl;
  27.  
  28. // This is because the array does actually contain its elements and not
  29. // merely a pointer to them. This allows it to avoid that extra memory
  30. // access and thus perform slightly better in high-demand situations.
  31. //
  32. // Note that this is only possible in array because it knows the size
  33. // at COMPILE TIME and therefore it cannot resize it at runtime.
  34. //
  35. // Vector cannot do this because it needs to be able to adjust the size
  36. // at runtime. Any dynamically sized container is going to have the
  37. // same issue.
  38. return 0;
  39. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
sizeof vec100 = 12
sizeof vec2   = 12
sizeof arr100 = 400
sizeof arr2   = 8