Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialise an Stl Vector of type T* from an array of type T

if I have an array such as:

struct S {... };

S m_aArr[256];

and I want to use this to construct a vector such as:

std::vector<S*> m_vecS;

Is there anyway to do this rather than looping through and pushing back &m_aArr[i] ? I understand that I cannot use the conventional method of using std::begin and std::end on the array since the vector is one of pointers and the original array is one of objects, and so we cannot just pass in a block of memory.

like image 532
makar Avatar asked Dec 02 '22 19:12

makar


1 Answers

You could use the standard library to do the iteration and pushing back for you:

std::transform(std::begin(m_aArr), std::end(m_aArr),
               std::back_inserter(m_vecS), std::addressof<S>);

This will transform each of the elements in m_aArr by applying the std::addressof<S> function to them. Each of the transformed elements is then push_backed into m_vecS by the std::back_inserter iterator.

To do this prior to C++11, you won't have access to std::begin, std::end, or std::addressof, so it'll look more like this:

std::transform(m_aArr, m_aArr + 256, std::back_inserter(m_vecS), boost::addressof<S>);

This uses boost::addressof.

like image 165
Joseph Mansfield Avatar answered Dec 14 '22 23:12

Joseph Mansfield