【发布时间】:2011-04-05 23:36:19
【问题描述】:
有人可以向我解释为什么下面的代码可以工作并产生正确的结果吗? v1.begin() 产生一个迭代器,但是在调试时,如果我在比较函数中检查 v1.begin() 的值,我会看到向量的第一个元素的值。
这是否与需要使用typename vector<T>::iterator 来命名模板内的迭代器这一事实有关?如果有人能详细说明,那就太好了
谢谢
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;
}
【问题讨论】:
-
iComp计算结果为false。所以我不明白这个问题! -
你是对的,我没有检查 iComp 的值,而只是检查了函数中的 v1、v2 和 v3 的值。我不知道是什么原因,但在 VC++ 2010 inisde 中将鼠标悬停在 v1、v2 和 v3 上时,函数显示三个变量的值为 3,所以我假设它会产生 True。太好了,这不是逻辑告诉我的。很抱歉没有仔细检查。
-
Visual C++ 有助于显示迭代器指向的内容。这就是你所看到的。
v1、v2和v3都是迭代器。 -
@Oli - 当您确定一种语言的逻辑而不是在您尝试学习它时,这可能会有所帮助;-)
-
赞成的问题:通过在调试器下使用 C++,我学到了很多。
标签: c++ templates vector iterator