As a C++ newbie, I am just discovering iterators. I realize that one can use either an int
or an iterators
for loop through any container. Consider for example
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(4);
v.push_back(8);
std::cout << "i is an int: ";
for (int i = 0; i<v.size();i++)
{
std::cout << v[i] << " ";
}
std::cout << std::endl;
std::cout << "i is an iterator: ";
for (std::vector<int>::iterator i = v.begin(); i!=v.end();i++)
{
std::cout << *i << " ";
}
std::cout << std::endl;
}
which outputs
i is an int: 1 4 8
i is an iterator: 1 4 8
Generally speaking,
- is there any advantage of using one or the other method?
- Is one faster than the other one?
- When should I use an
int
and when should I use aniterator
?