2017-11-25 176 views
0

我有以下數據結構: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語句的情況下實現的功能?

+1

不需要我填寫評論 –

+0

根據你的要求,你似乎並不需要「主動」成員開始。 – NiVeR

+0

反轉條件,在「if」裏面「做點什麼」? –

回答

1

只需編寫包裝器迭代器類和範圍類。

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

如果你真的想消除檢查,不只是將其隱藏,然後使用一個單獨的容器來存儲元素的索引,其中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