0

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?

4
  • do you mean size as in number of elements in array (5) or size of int? Commented Oct 20, 2014 at 12:47
  • you can initialise a vector by using start and end iterators vector<int*>(int* start,int* end) - this assumes they are contiguous in memory Commented Oct 20, 2014 at 12:49
  • @Jimmy You're talking about using std::vector's iterator ctor I believe, which won't work cause I'm constructing a std::vector of int*s not a std::vector of ints. Commented Oct 20, 2014 at 12:53
  • 1
    You can probably use boost:: transform_iterator to adapt begin(foo) and end(foo). Commented Oct 21, 2014 at 4:28

1 Answer 1

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)
    };
Sign up to request clarification or add additional context in comments.

2 Comments

I have to say that template deduction is pretty cool. However, not quite what I was looking for. That can be just above the definition of vec without a templatized function. It requires a copy construction, even if a separate function isn't called. The boost::make_transform_iterator is exactly what I'm looking for... but I don't have access to boost :(
@JonathanMee I believe copy elision is in effect here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.