【发布时间】:2018-09-11 02:18:02
【问题描述】:
我用 C++ 编写了一个示例代码来检查向量中的元素:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> myVec;
myVec.push_back(1);
myVec.push_back(2);
myVec.push_back(3);
myVec.push_back(4);
vector<int>::iterator it = NULL; // compilation error
for(it = myVec.begin(); it != NULL; it++) // compilation error
{
if((*it == 3)
{
cout << "3 is found\n";
break;
}
}
if(it == NULL) // compilation error
{
cout << "3 is not found\n";
}
return 0;
}
在编译此代码时,我在代码中标记为 cmets 的以下行中遇到编译错误。
我已经读到迭代器只是指针应该如何行走的包装器。那么,为什么不能设置迭代器或将其与 NULL 进行比较?
任何帮助将不胜感激。
【问题讨论】:
-
"..我读过迭代器只是指针如何包装..." 指针是迭代器,但迭代器不一定是指针。
-
那么哪些迭代器可以设置或与 NULL 比较?
-
"那么哪些迭代器可以设置或与 NULL 进行比较?"那些是指针。而不是那些不是指针的。
-
@BhawandeepSingla 仅当您这样设计时。标准库中没有保证。为什么不想和
myVec.end()比较? -
@BhawandeepSingla -- 仅供参考,旧的 Visual C++ 编译器(6.0 及以下)会接受您的代码。为什么?只是因为命运使然,Visual C++ 6.0 将向量迭代器实现为指针。所以你不会知道从技术上讲,你的代码被破坏了。你以后会知道困难的方式,因为不幸的是从 VC 6.0 升级到更高版本的人之一,突然之间代码拒绝编译。这个故事的寓意是将迭代器视为迭代器——不要假设它们是指针。