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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With