I am currently working on a c++ school project with some friends.
Before when i had vectors in c++ i did something like this to use them :
unsigned int i = 0;
while (i != myVector.size())
{
doSomething(myVector[i]);
i++;
}
But during this project my friends were not happy seeing me using vectors like this and asked me to use iterators. I don't really enjoy iterators because their syntax is quite hard to remember but my friends said that is was better using them because it works faster. And since we are working in a big project with a lot of vectors it was crucial using iterators.
Time has passed and i'm still using them even if i still can't remember their syntax but i wanted to see if the iterator method was really faster them the "unsigned int" method.
So i made this 2 programs:
First program using the unsigned int method:
#include <vector>
#include <string>
#include <iostream>
int main()
{
std::string str = "This is a string";
int i = 0;
std::vector<std::string> vec;
while (i != 10000000)
{
vec.push_back(str);
i++;
}
unsigned int j = 0;
while (j != vec.size())
{
std::cout << vec[j] << std::endl;
j++;
}
return (0);
}
And the second program using the iterator method:
#include <vector>
#include <string>
#include <iostream>
int main()
{
std::string str = "This is a string";
int i = 0;
std::vector<std::string> vec;
while (i != 10000000)
{
vec.push_back(str);
i++;
}
std::vector<std::string>::iterator it;
it = vec.begin();
while (it != vec.end())
{
std::cout << *it << std::endl;
it++;
}
return (0);
}
As you can see both programs will first create a vector with a size of 10 000 000 (i've put a big size so if there's a difference in time it will be easier to notice) and then i will just print the string in the vector but using the two different methods.
I used time on linux to know the execution time of each program like this:
time ./a.out
And here's the result:
The unsigned int method:
real 0m39,391s
user 0m5,463s
sys 0m21,108s
The iterator method:
real 0m39,436s
user 0m5,972s
sys 0m20,652s
And ......... it's the same time ?! There's just a negligible less than 1 second difference between both and it's a vector with 10 million strings in it.
So i was wondering is there really a difference between this two methods and are iterators really better to use ?