问题
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