問題描述
我有一個循環代碼塊,其中我循環了 enum 類
的所有成員.
I have a recurrent chunk of code where I loop over all the members of an enum class
.
與新的 基于范圍的 for
相比,我目前使用的 for
循環看起來非常笨拙.
The for
loop that I currently use looks very unwieldly compared to the new range-based for
.
有什么方法可以利用 C++11 的新特性來減少當前 for
循環的冗長?
Is there any way to take advantage of new C++11 features to cut down on the verbosity for my current for
loop?
我想改進的當前代碼:
enum class COLOR
{
Blue,
Red,
Green,
Purple,
First=Blue,
Last=Purple
};
inline COLOR operator++( COLOR& x ) { return x = (COLOR)(((int)(x) + 1)); }
int main(int argc, char** argv)
{
// any way to improve the next line with range-based for?
for( COLOR c=COLOR::First; c!=COLOR::Last; ++c )
{
// do work
}
return 0;
}
換句話說,如果我能做這樣的事情就好了:
In other words, it would be nice if I could do something like:
for( const auto& c : COLOR )
{
// do work
}
推薦答案
用枚舉本身作為迭代器來迭代枚舉是一個糟糕的主意,我建議使用實際的迭代器,如 deft_code 的答案.但如果這真的是你想要的:
Iterating enumerations with the enumeration itself as an iterator is a poor idea, and I recommend using an actual iterator as in deft_code's answer. But if this is really what you want:
COLOR operator++(COLOR& x) {
return x = (COLOR)(std::underlying_type<COLOR>::type(x) + 1);
}
COLOR operator*(COLOR c) {
return c;
}
COLOR begin(COLOR r) {
return COLOR::First;
}
COLOR end(COLOR r) {
COLOR l=COLOR::Last;
return ++l;
}
int main() {
//note the parenthesis after COLOR to make an instance
for(const auto& c : COLOR()) {
//do work
}
return 0;
}
在這里工作:http://ideone.com/cyTGD8
const COLOR COLORS[] = {COLOR::Blue, COLOR::Red, COLOR::Green, COLOR::Purple};
const COLOR (&COLORREF)[(int)COLOR::Last+1] = COLORS;
int main() {
for(const auto& c : COLORS) {
//do work
}
return 0;
}
如下所示:http://coliru.stacked-crooked.com/a/5d356cc91556d6ef
(如果顏色數量與數組中的元素數量不匹配,單獨的定義和數組的引用會導致編譯器錯誤.非常容易安全檢查.)
(The separate defintinion and the reference of the array makes it a compiler error if the number of colors doesn't match the number of elements in the array. Excellent easy safety check.)
這篇關于允許基于范圍的 For 與枚舉類?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!