c++ - 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
希望任何人都可以分享解释或将我引导到可用资源。
解决方案
在经典循环中:
auto it = c.begin()
-it
是一个迭代器。要访问它所引用的内容,您需要取消引用它,您可以使用*it
. *
那里并不意味着指针,它意味着取消引用(从技术上讲,在迭代器上,它是对 的调用operator*
)。
另请参阅https://en.cppreference.com/w/cpp/iterator
在基于范围的循环中:
for (auto &i : c)
- 在这里您可以直接返回对容器中元素的引用。不涉及迭代器。
推荐阅读
- android - 通过retrofit2发送文件时发现错误'Response{protocol=http/1.1, code=404, message=Not Found, url=url}'
- reactjs - 在 React Native 中推送到另一个屏幕时必须使用解构道具分配
- java - 如何为 JPA L2 缓存配置 WIldfly infinispan 子系统?
- python - 如何将数据附加到 DataFrame
- ios - MKMarkerAnnotationView 标题未显示
- django - Django 重定向不适用于 dropzone.js
- javascript - 切换反应状态
- c# - 组件内的多个系统
- angular - 如何仅将外部脚本包含到组件中?
- android - 安卓黑白主题