const向量的C向量数组元素 [英] const vector of Pointers to C-Style Array Elements

查看:171
本文介绍了const向量的C向量数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个C风格的数组: int foo [] {1,2,3,4,5};

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

现在我想构造一个 const std :: vector< int *> pFoo {& foo [0],& foo [1],& foo [2],& foo [3],& foo [4]};

我可以使用 initializer_list ,只要我知道所有的元素。但是说,我只是通过 foo 和它的大小。在设计时可以初始化 pFoo 而不知道 foo 的大小?

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?

推荐答案

您可以创建一个代理函数来初始化你的向量。这使用模板扣除自动查找数组的大小。

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 << " ";
}

或者,如果您可以使用Boost,您可以使用 boost :: make_transform_iterator

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)
    };

这篇关于const向量的C向量数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆