for 循环 - 迭代特定元素

for loop - iterate over specific elements

本文关键字:元素 迭代 循环 for      更新时间:2023-10-16

我有以下数据结构:

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;
}