【问题标题】:Compilation error while comparing iterator to NULL in C++在 C++ 中将迭代器与 NULL 进行比较时出现编译错误
【发布时间】: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 升级到更高版本的人之一,突然之间代码拒绝编译。这个故事的寓意是将迭代器视为迭代器——不要假设它们是指针。

标签: c++ pointers stl iterator


【解决方案1】:

您应该将itmyVec.end() 进行比较。这就是向量迭代器的工作方式。

所以,

vector<int>::iterator it = NULL; // compilation error
for(it = myVec.begin(); it != NULL; it++)  // compilation error
...
if(it == NULL) // compilation error

变成

vector<int>::iterator it = myVec.begin();
for (; it != myVec.end(); it++)
...
if (it == myVec.end())

auto it = myVec.begin();
for (; it != myVec.end(); it++)
...
if (it == myVec.end())

【讨论】:

  • 既然你列出了可能性,你应该建议for (auto item : myVec)
  • @YSC,他想知道如何使用迭代器,他在循环结束后使用迭代器..
【解决方案2】:

您应该将其与myVec.end() 进行比较,而不是NULL

Iterator 是一个类,而不是一个指针。所以和NULL比较是没有意义的。你可以在这里查看:iterator

【讨论】:

  • 我知道。但我想知道 NOT NULL 背后的原因。
  • @BhawandeepSingla 迭代器是一个类,而不是一个指针。所以和NULL比较是没有意义的。
  • 一个interator实例是一个值,而不是一个指针。迭代器是类这一事实与此无关。
【解决方案3】:

我已经读到迭代器只是指针应该如何行走的包装器。那么,为什么不能设置迭代器或将其与 NULL 进行比较?

迭代器不仅仅是指针的“包装器”。但让我们假装它确实如此。是不是可以和NULL比较?

让我们退后一步,想想其他东西的“包装”,比如int

struct WrapperOfInt
{
    int x;
};

然后实例化它:

WrapperOfInt w;

那么你能把它和int比较一下吗?

w == 1;

不,你不能。 WrapperOfInt 不是 int,句号。你无法比较它们。

以此类推,即使迭代器是指针的包装器,它也不是指针。您无法将其与 NULL 进行比较。

【讨论】:

    猜你喜欢
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 2016-02-07
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多