Vector iterator

Greetings,

I have troubles understanding the iterator concept with respect to vectors.
Consider the following example code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>
 
static bool abs_compare(int a, int b)
{
    return (std::abs(a) < std::abs(b));
}
 
int main()
{
    std::vector<int> v{ 3, 1, -14, 1, 5, 9 }; 
    std::vector<int>::iterator result;
 
    result = std::max_element(v.begin(), v.end());
    std::cout << "max element at: " << std::distance(v.begin(), result) << '\n';
 
    result = std::max_element(v.begin(), v.end(), abs_compare);
    std::cout << "max element (absolute) at: " << std::distance(v.begin(), result);
}


Firstly, is the iterator an actual number, e.g. does v.begin give a 0, namely the first index of vector v?
Secondly, why do I need the distance function? Can't I simply cout<<result ?

Regards!
Firstly, is the iterator an actual number, e.g. does v.begin give a 0, namely the first index of vector v?
No. An iterator can be thought of as analogous to a pointer. Conceptually, an iterator is more general than an index, since it can be used to iterate sequences that can't be indexed, such as a linked list.

Secondly, why do I need the distance function? Can't I simply cout<<result ?
Iterators don't normally have operator<<() overloads, so they can't be printed, but even if you could print them, all you'd get would be a memory address. Like a pointer, an iterator by itself doesn't know how far from the start of the structure it's pointing.
You can dereference the iterator (*result) but this will just give you the element at that position.
You can also subtract instead of calling std::distance() (v.begin() - result), but for a vector iterator this is equivalent to std::distance().
Firstly, is the iterator an actual number, e.g. does v.begin give a 0, namely the first index of vector v?

You can think of an iterator as being semantically similar to a pointer.

So, if you have an iterator itr, the value of the element it's "pointing" to would be *itr.

Secondly, why do I need the distance function? Can't I simply cout<<result

Hopefully, my first answer explains that. result isn't an index.
Last edited on
Thank you guys, that makes it clearer!
I figured it looked similar to a pointer. I guess there are many concepts to learn for me.
You're welcome. Glad it helped!
Topic archived. No new replies allowed.