简体   繁体   中英

How to initialize a shared_ptr as an array of int in C++

I have a class variable defined like this:

std::shared_ptr<int[]> variable;

I want to make it store ints from 0 to 10

so that when I call variable[1] it returns 1 and so on.

I would use the std::array syntax like this

#include <array>
#include <iostream>
#include <memory>

int main()
{
    // use the std::array syntax it will make the dereferenced smartpointer
    // directly behave like an array. You can use index operator and even
    // use it in range based for loops directly
    auto variables = std::make_shared<std::array<int, 10>>();

    for (std::size_t n = 0ul; n < variables->size(); ++n)
    {
        (*variables)[n] = n;
    }

    for (const int value : *variables)
    {
        std::cout << value << " ";
    }

    return 0;
}

How to initialize a shared_ptr as an array of int in C++

If there are only a limited number of values you'd like in the array, the most practical may be to use new[] with an initializer:

std::shared_ptr<int[]> variable(new int[]{0,1,2,3,4,5,6,7,8,9,10});

If you want to initialize it with a bigger range, you could create a helper that uses an index_sequence and pack expansion:

template<std::size_t N, class T>
std::shared_ptr<T[]> make_shared_iota(T start, T stride) {
    return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
        return std::shared_ptr<T[]>(new T[]{start + stride * T{Is}...});
    }(std::make_index_sequence<N>());
}

// create an array of 20 `int` {3,5,7,...,37,39,41}
auto variable = make_shared_iota<20>(3, 2);

or with a little more freedom, using a functor to provide a formula for calculating the values to initialize the array with:

template<std::size_t N, class Func>
auto make_shared_iota(Func&& func) {
    using type = decltype(func(std::size_t{}));

    return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
        return std::shared_ptr<type[]>(new type[]{std::invoke(func, Is)...});
    }(std::make_index_sequence<N>());
}

// create an array of 20 `int` {3,5,7,...,37,39,41}
auto variable = make_shared_iota<20>([](std::size_t x) {
                    return static_cast<int>(3 + x * 2); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM