C++11版本
...
//.hpp
enum class Week {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
//用数组容器包装
constexpr initializer_list<Week> Weeks = {
Week::Monday,
Week::Tuesday,
Week::Wednesday,
Week::Thursday,
Week::Friday,
Week::Saturday
Week::Sunday
};
//重载<<操作符,以适配Week的打印
ostream& operator << (ostream& os, const Week week);
//.cpp
ostream& operator << (ostream& os, const Week week)
{
os << static_cast<int>(week) ;
return os;
}
const auto week = Week::Sunday;
//遍历1,使用for (elem : Container)语法
for (const auto& w : Weeks) {
cout << w << endl;
if (w == week) {
//do something
break;
}
}
//遍历2,使用迭代器
for (auto it = Weeks.begin(); it != Weeks.end(); ++it) {
cout << *it << endl;
if (*it == week) {
//do something
break;
}
}
C++98版本
//.hpp
enum class Week {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};
ostream& operator << (ostream& os, const Week week);
//.cpp
ostream& operator << (ostream& os, const Week week)
{
os << static_cast<int>(week);
return os;
}
const Week Weeks[] = {
Week::Monday,
Week::Tuesday,
Week::Wednesday,
Week::Thursday,
Week::Friday,
Week::Saturday
Week::Sunday
};
//遍历
const Week week = Week::Sunday;
const unsigned wCount = sizeof(Weeks) / sizeof(Week);
for (unsigned i = 0; i < wCount; ++i) {
cout << Weeks[i] << endl;
if (Weeks[i] == week) {
//do something
...
break;
}
}
|