Why is this not ok

why the first construction is ok but second is not?
1
2
auto p(std::find(v.begin(), v.end(), 5)); 
int *p(std::find(v.begin(), v.end(), 5));
Last edited on
Don't keep us in suspense.
What, exactly, is v?
Presumably because the type of the expression std::find(v.begin(), v.end(), 5) is not convertible to int*.

In particular, if v is a std::vector<int>, then v.begin() is std::vector<int>::iterator.
Note that all pointers are iterators, but not all iterators are pointers.
1
2
3
4
5
6
7
8
9
10
11
#include <algorithm>

int main() {
    int v1[] {1, 3, 5, 7, 9};
    int *p1(std::find(std::begin(v1), std::end(v1), 5));

    std::vector<int> v2 {1, 3, 5, 7, 9};
    std::vector<int>::iterator p2(std::find(std::begin(v2), std::end(v2), 5));

    // that ugly syntax is one of the reasons to use auto
}
Topic archived. No new replies allowed.