• Advertisement
Sign in to follow this  

std::initializer list as array

This topic is 1459 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Was cleaning up some older code and wanted to add an initializer_list to a simple wrapper class.  The data from the list is to be passed to an API function that accepts a pointer and length.

 

I was thinking of doing something like:

SetFloatArray(&*list.begin(),list.size());

Is this 'kosher'?  I'd like to avoid having to create a temporary store to copy the data.

 

Or perhaps just:

SetFloatArray(list.begin(),list.size());

would work?  http://en.cppreference.com/w/cpp/utility/initializer_list states that the iterator type is a pointer.

Edited by Ryan_001

Share this post


Link to post
Share on other sites
Advertisement

That's going to work only if your data is contiguous in memory.

If your list container is an std::list, then the data is not continuous, and your example wont work.. An std::vector will work as expected, but in that case you should use vec.data() or &vec[0].

On the other hand, you could pass in the iterator itself (which acts as a pointer as far as dereferencing goes, but is not one, you can't pass an iterator where a pointer is expected), and then inside the function use it++ to move forward no matter the container type until you've done it container.size() times.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement