for循环 - 遍历特定元素
问题描述:
我有以下数据结构:for循环 - 遍历特定元素
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和/或continue语句的情况下实现的功能?
答
只需编写包装器迭代器类和范围类。
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;
}
答
如果你真的想消除检查,不只是将其隐藏,然后使用一个单独的容器来存储元素的索引,其中active
是真实的,并将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<std::string>
更换您T
如果你的编译器已经支持std::optional
。
不需要我填写评论 –
根据你的要求,你似乎并不需要“主动”成员开始。 – NiVeR
反转条件,在“if”里面“做点什么”? –