0

For example,

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

I can write

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

But for JJ z[100], I can't write {6,6,6....,6}, so what can I do with that?

5
  • Are you using a compiler supporting C++11 or even C++14 ? If so have a look at std::array Commented Mar 9, 2016 at 10:18
  • 2
    You could use std::vector<JJ> z(100, 6); to create 100 elements with value 6. Commented Mar 9, 2016 at 10:24
  • @BoPersson Yes, but what if there are more arguments in the constructor? Besides, there is no way no use JJ z[100] to make it without stl? Commented Mar 9, 2016 at 10:29
  • You might want to specify what you mean by "array". It has more than one meaning in C++. For example, a C-style array, the std::array templated container type in the standard library, possibly even usage of other standard containers (like std::vector). Each choice has different advantages, depending on what you are ACTUALLY doing. Containers are often considered vastly preferable to C-style arrays, even if beginners think otherwise. Commented Mar 9, 2016 at 10:29
  • @Peter The information in your last sentence informs me sth I didn't know. I meant C-style arrays. It seems with C-style arrays, it can't be done. Commented Mar 9, 2016 at 10:34

1 Answer 1

3

If std::vector doesn't fit your needs with

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

You may use 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);
}

And then

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

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

The usage of namespace detail is unnecessary.
@Peter: It does compile Demo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.