首页 > 解决方案 > for-loop:指针变量作为 if 语句中的条件的必要性

问题描述

我不明白为什么 if 语句的条件需要是一个指针。我假设一个正常的变量调用不会有任何抱怨。

试图从 cppreference 了解 std::vector::erase,对那里的示例很感兴趣(https://en.cppreference.com/w/cpp/container/vector/erase

#include <vector>
#include <iostream>

int main( )
{
    std::vector<int> c{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    for (auto &i : c) {
        std::cout << i << " ";
    }
    std::cout << '\n';
    // Erase all even numbers (C++11 and later)
    for (auto it = c.begin(); it != c.end(); ) {
        if (*it % 2 == 0) {
            it = c.erase(it); // THE LINE ABOVE THIS
        } else {
            ++it;
        }
    }
    for (auto &i : c) {
        std::cout << i << " ";
    }
    std::cout << '\n';
}

输出

0 1 2 3 4 5 6 7 8 9 
1 3 5 7 9 

希望任何人都可以分享解释或将我引导到可用资源。

标签: c++for-loopif-statement

解决方案


在经典循环中:

auto it = c.begin()-it是一个迭代器。要访问它所引用的内容,您需要取消引用它,您可以使用*it. *那里并不意味着指针,它意味着取消引用(从技术上讲,在迭代器上,它是对 的调用operator*)。

另请参阅https://en.cppreference.com/w/cpp/iterator

在基于范围的循环中:

for (auto &i : c)- 在这里您可以直接返回对容器中元素的引用。不涉及迭代器。


推荐阅读