简体   繁体   中英

vector iterator and template functions

Can somebody explain to me why the code below works and produce true? v1.begin() produces an iterator but when debugging if I inspect the value of v1.begin() inside the compare function I see the value of the first element of the vector.

Is this related to the fact that one needs to use typename vector<T>::iterator it to name an iterator inside a template? It would be great if somebody could elaborate on this

Thanks

template<class U, class V> bool compare(const U &v1, const U &v2, const V &v3) {
    if ((v1 == v2) && (v2 == v3) ){
        return 1;
    } else {
        return 0;
    }
}


#include<iostream>
#include<vector>
using namespace std;

int main() {

    vector<int>     v1(10,3);
    vector<int>     v2(10,3);
    bool iComp = compare(v1.begin(), v1.begin() + 2, v2.begin());
    cout << typeid(v1.begin()).name() << "    "  << *v2.begin() << endl;

    return 1;
}

compare returns true if and only if all three iterators point to the same object. If the iterators pointed to objects of different types, there could be a compilation error.

The iterators point to different objects, because the arguments are all different, so compare returns false . This result is thrown away.

Then the program prints a unique string identifying the type std::vector< int >::iterator . This might be a long string mentioning the fragments std , vector , and iterator , or it might be simply pi for "pointer to integer," if the <vector> implementation uses typedef T *iterator .

Finally it prints 10 because that is the first value in v2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM