std :: vector <int>到std :: vector <enum>

时间:2019-09-25 23:04:48

标签: c++ c++11 c++14

我有一个数组std::vector<int>和一个enum class Foo : int。是否有比reinterpret_cast更好的投射或转换方式?

std::vector<int> v;
auto& c = *reinterpret_cast<std::vector<Foo>*>(&v);

1 个答案:

答案 0 :(得分:5)

https://godbolt.org/z/M6ofkF

static_caststd::transform组合在一起。

#include <algorithm>
#include <vector>
#include <cassert>

enum class Foo : int {
   A = 0,
   B = 1,
   C = 2,
   D = 3,
   E = 4,
   F = 5
};

std::vector<Foo> convert(std::vector<int> const &in) {
  std::vector<Foo> out;
  out.reserve(in.size());

  std::transform(in.begin(), in.end(), std::back_inserter(out),
                 [](int n) { return static_cast<Foo>(n); });
  return out;
}

int main() {
  std::vector<int> vec{1, 2, 3, 4, 5};
  std::vector<Foo> c = convert(vec);

  assert(c[3] == Foo::E);

  return 0;
}

参考:How to cast int to enum in C++?