【问题标题】:Is there a way to initialize a array of some objects with the same parameter for the constructer function?有没有办法为构造函数初始化具有相同参数的一些对象数组?
【发布时间】:2016-06-23 15:36:26
【问题描述】:

例如,

class JJ
{
public:
    JJ(int c)
    {
        a = c;
    }
    int a;
};

我会写

JJ z[2] = {6,6};

但是对于JJ z[100],我不能写{6,6,6....,6},那我该怎么办呢?

【问题讨论】:

  • 您使用的是支持 C++11 甚至 C++14 的编译器吗?如果是这样,请查看 std::array
  • 你可以使用std::vector<JJ> z(100, 6);创建100个值为6的元素。
  • @BoPersson 是的,但是如果构造函数中有更多参数怎么办?再说了,没有stl就没有办法用JJ z[100]做吧?
  • 您可能想要指定“数组”的含义。它在 C++ 中具有不止一种含义。例如,C 风格的数组,标准库中的std::array 模板容器类型,甚至可能使用其他标准容器(如std::vector)。每种选择都有不同的优势,具体取决于您实际在做什么。容器通常被认为比 C 风格的数组更可取,即使初学者不这么认为。
  • @Peter 你最后一句话中的信息告诉我……我不知道。我的意思是 C 风格的数组。好像用 C 风格的数组,是做不到的。

标签: c++


【解决方案1】:

如果std::vector 不符合您的需求

std::vector<JJ> v(100, JJ(6));

您可以使用std::array

namespace detail
{

    template <std::size_t N, std::size_t...Is, typename T>
    std::array<T, N> make_array(std::index_sequence<Is...>, const T& t)
    {
        return {{(static_cast<void>(Is), t)...}};
    }

}


template <std::size_t N, typename T>
std::array<T, N> make_array(const T& t)
{
    return detail::make_array<N>(std::make_index_sequence<N>{}, t);
}

然后

std::array<JJ, 100> a = make_array<100>(JJ(6));

Demo

【讨论】:

  • 命名空间detail的使用是不必要的。
  • @Peter:它确实编译了Demo
猜你喜欢
  • 1970-01-01
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
相关资源
最近更新 更多