Jump to content

  • Log In with Google      Sign In   
  • Create Account

std::initializer list as array


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 Ryan_001   Prime Members   -  Reputation: 1457

Like
0Likes
Like

Posted 23 January 2014 - 04:29 AM

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, 23 January 2014 - 04:48 AM.


Sponsor:

#2 Strewya   Members   -  Reputation: 1581

Like
0Likes
Like

Posted 23 January 2014 - 05:26 AM

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.


devstropo.blogspot.com - Random stuff about my gamedev hobby


#3 Ryan_001   Prime Members   -  Reputation: 1457

Like
0Likes
Like

Posted 23 January 2014 - 05:40 AM

Sorry I guess I should've specified more clearly.  The container is a std::intializer_list<T>.



#4 Wooh   Members   -  Reputation: 652

Like
0Likes
Like

Posted 23 January 2014 - 06:49 AM

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.

Yes this should work. std::initializer_list stores the elements in an array and the begin() function returns a pointer to the first element in that array.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS