[英]vector iterator and template functions
Can somebody explain to me why the code below works and produce true? 有人可以向我解释下面的代码为什么起作用并产生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. v1.begin()
产生一个迭代器,但是在调试时,如果我检查比较函数内部的v1.begin()
值,我会看到向量的第一个元素的值。
Is this related to the fact that one needs to use typename vector<T>::iterator
it to name an iterator inside a template? 这是否与需要使用
typename vector<T>::iterator
来命名模板中的迭代器有关? 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. 当且仅当所有三个迭代器都指向同一个对象时,
compare
返回true
。 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
. 迭代器指向不同的对象,因为参数都不同,所以
compare
返回false
。 This result is thrown away. 这个结果被扔掉了。
Then the program prints a unique string identifying the type std::vector< int >::iterator
. 然后程序打印一个唯一的字符串,标识类型为
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
. 如果
<vector>
实现使用typedef T *iterator
,则这可能是一个很长的字符串,其中提到了片段std
, vector
和iterator
,或者对于“指向整数的指针”可能只是pi
。
Finally it prints 10
because that is the first value in v2
. 最后,它打印
10
因为那是v2
的第一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.