const vector of Pointers to C-Style Array Elements

淺唱寂寞╮ 提交于 2019-12-23 05:25:51

问题


Say I have a C-style array like this: int foo[]{1, 2, 3, 4, 5};

Now I want to construct a const std::vector<int*> pFoo{&foo[0], &foo[1], &foo[2], &foo[3], &foo[4]};

I can use the initializer_list as long as I know all the elements. But say that I was just passed foo and it's size. Can I initialize pFoo without knowing the size of foo at design time?


回答1:


You can create a "proxy" function that initializes your vector. This uses template deduction to find the size of the array automatically.

template <typename T, std::size_t N>
std::vector<int*> init_vector(T (&foo)[N])
{
    std::vector<int*> vec;
    for (std::size_t i = 0; i < N; ++i)
    {
        vec.push_back(&foo[i]);
    }
    return vec;
}

int main()
{
    int foo[] {1, 2, 3, 4, 5};
    const std::vector<int*> vec = init_vector(foo);
    for (auto v : vec) std::cout << *v << " ";
}

Alternatively, if you're able to use Boost, you can use boost::make_transform_iterator:

int* convert_to_ptr(int& i)
{
    return &i;
}

int main()
{
    int foo[] {1, 2, 3, 4, 5};
    const std::vector<int*> vec { 
        boost::make_transform_iterator(std::begin(foo), convert_to_ptr),
        boost::make_transform_iterator(std::end(foo),   convert_to_ptr)
    };


来源:https://stackoverflow.com/questions/26466049/const-vector-of-pointers-to-c-style-array-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!