如何在类构造函数中使用参数初始化std :: array的大小?

acg*_*ant 1 c++ std c++11

例如:

#Include <array>

class UnionFind final {
 public:
  explicit UnionFind(int numbers) {
    // ???
  }

 private:
  std::array<int, ???> array_;
};
Run Code Online (Sandbox Code Playgroud)

我想初始化array_std::array<int, numbers>在构造函数UnionFind(int numbers),但我不知道该怎么做.

son*_*yao 7

必须在编译时指定std :: array的大小,例如:

template <std::size_t numbers>
class UnionFind final {
public:
  UnionFind() {}

private:
  std::array<int, numbers> array_;
};
Run Code Online (Sandbox Code Playgroud)

然后(假设大小固定为3)

UnionFind<3> u;
Run Code Online (Sandbox Code Playgroud)

如果要在运行时指定大小,可能需要使用std :: vector:

class UnionFind final {
public:
  explicit UnionFind(int numbers) : array_(numbers) {}

private:
  std::vector<int> array_;
};
Run Code Online (Sandbox Code Playgroud)

  • 最好使用`size_t`作为模板参数. (2认同)