for 循环 - 迭代特定元素
for loop - iterate over specific elements
我有以下数据结构:
struct T
{
std::string name;
bool active;
};
然后我想迭代 T 的向量,但仅适用于活动元素:
std::vector<T> myVector;
//fill vector
for(const auto& item: myVector)
{
if(!item.active)
{
continue;
}
//do something;
}
是否有任何功能可以在不使用 if 和/或继续语句的情况下实现这一目标?
如果您真的想消除检查而不仅仅是隐藏它,请使用单独的容器来存储active
为 true 的元素索引,并将for
循环替换为一个遍历另一个容器中所有索引的循环。
确保每次向量更改时都会更新索引容器。
#include <string>
#include <vector>
struct T
{
std::string name;
bool active;
};
int main()
{
std::vector<T> myVector;
using Index = decltype(myVector)::size_type;
std::vector<Index> indicesActive;
// ...
for (auto index : indicesActive)
{
auto const& item = myVector[index];
// ...
}
}
如果不了解问题的背景,很难说这是否值得麻烦。
请注意,如果您的编译器已经支持std::optional
,您可能可以将T
替换为std::optional<std::string>
。
只需编写包装迭代器类和范围类。
https://gist.github.com/yumetodo/b0f82fc44e0e4d842c45f7596a6a0b49
这是实现迭代器包装迭代器的示例。
另一种方法是使用Sprout。
sprout::optional
是容器类型,因此您可以像下面这样写:
std::vector<sprout::optional<std::string>> myVector;
//fill vector
for(auto&& e : myVector) for(auto&& s : e)
{
//do something;
}
相关文章:
- 擦除while循环中迭代的元素
- 对于set上的循环-获取next元素迭代器
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 高级选择排序 - 在一次迭代中搜索两个元素
- 访问要输出的矢量迭代器元素
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 位集元素迭代的抽象
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- 调用 erase() 函数是否也会在擦除元素之前更改迭代器值?
- 为什么 min_element() 返回最小元素的索引,而不是迭代器?
- 如何将元素插入和迭代到这种映射.C++
- 如何通过查找迭代器结果分配给一组对的元素
- 在迭代期间添加到 std::unordered_set(或 unordered_map)中的元素是否会在迭代期间访问?
- 使用 Rcpp 加速替换迭代算法中的列表和向量元素是否合法?
- C++:在进行切片时对迭代器的约定,特别是对于访问最后一个元素并最终将其删除
- 如何在集合中迭代替代元素(或进行特定大小的飞跃)?
- 无法将 std::set 中的元素迭代器插入到 std::list
- 使用std :: remove_reference获取STL容器的元素迭代器
- C++ 从地图的第二个元素迭代
- 在未排序向量中查找第 k 个最小元素(迭代)