I've just written a tiny C++ program just to understand how vectors work with memory and what's happen during run-time.
There is my code :
#include <iostream>
#include <cstdio>
#include <ctime>
#include <vector>
int main(){
clock_t start, end;
int x;
std::vector<int> a(5, 100);
start = clock();
for(int i = 0 ; i <= 900000000 ; i++){
x = a[0];
x = a[1];
x = a[2];
x = a[3];
x = a[4];
}
end = clock();
clock_t duration = end - start;
double durationPerSec = duration / (double)CLOCKS_PER_SEC;
std::cout << "Run-time : " << durationPerSec << std::endl;
return 0;
}
And i got this output :
Run-time : 18.7843
When i write the same code by replacing the vector by a dynamic array the run-time duration is more acceptable :
Run-time : 2.9526
I know this code is quite stupid but i wonder why run-time is so long when i use the vector ? Is that because i use it in the wrong way or just because there's something that i don't understand ?
Thanks for replying.