指针的常量向量C数组元素 [英] const vector of Pointers to C-Style Array Elements
问题描述
说我有一个C风格的数组是这样的: INT富[] {1,2,3,4,5};
Say I have a C-style array like this: int foo[]{1, 2, 3, 4, 5};
现在我想建立一个常量的std ::矢量<为int *> PFOO {&放大器;富[0],&安培;富[1],&安培;富[2],和放大器;富[3],和放大器;为foo [4]};
我可以使用 initializer_list
只要我知道的所有元素。但是说,我只是通过富
和它的大小。我可以初始化 PFOO
不知道富
的尺寸在设计时?
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?
推荐答案
您可以创建一个代理功能,您的初始化向量。这将使用<一个href=\"https://stackoverflow.com/questions/437150/can-someone-explain-this-template-$c$c-that-gives-me-the-size-of-an-array\">template扣除的自动查找数组的大小。
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 :
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)
};
这篇关于指针的常量向量C数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!