c++ - 如何在 C++ 中双向循环迭代 4 个枚举类值?

标签 c++ iteration c++17 c++20 enum-class

我有:

enum class orientation {
  North,
  East,
  South,
  West
};

我想向左(北 => 西)和向右(西 => 北)旋转它的实例。
但我不想将它们转换为数字,因为它会损害可读性和意图,而且从最后一个数字跳到第一个再跳回很奇怪。

我想出了很多解决方案,但都有些蹩脚:(

最佳答案

因为它们是有序的:

constexpr auto rotate(orientation o, int n) -> orientation {
    // convert to int
    int dir = (int)o;
    // rotate as an int
    dir = (dir + n) % 4;
    // account for negatives
    if (dir < 0) {
        dir += 4;
    }
    // and then convert back
    return orientation{dir};
}

您可以检查:
static_assert(rotate(orientation::North, 1) == orientation::East);
static_assert(rotate(orientation::North, -1) == orientation::West);

我选择了整数来表示“向右转 90 度的次数”,但您可以根据实际问题进行调整。或者添加辅助函数,如:
constexpr auto rotate_left(orientation o) -> orientation {
    return rotate(o, -1);
}

constexpr auto rotate_right(orientation o) -> orientation {
    return rotate(o, 1);
}

关于c++ - 如何在 C++ 中双向循环迭代 4 个枚举类值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61374507/

相关文章:

c++ - 使用 cppcheck 进行多行抑制

c++ - 从 pcl::people::Person Cluster<Point> 中提取点云

c++ - 外部 C 和结构方法

jquery .each 迭代

python - 数据帧分割和丢弃

c++ - 在 Eclipse 上启用 C++17 以使用 `std::byte`

c++ - 为什么 std::shared_ptr 没有 operator->*?

c++ - 为什么会出现访问冲突运行时错误?

c++ - 如何使用 optional 元素初始化 C++17 对 vector

C++在编译时在两个变量之间交替