0

This task might seem esoteric and dangerous but it's for some highly optimized code (admittedly I yet have to do actual benching). However I have an std::vector<unsigned long long int> and want to turn it into a std::vector<unsigned short> where each of the long long ints (64 bit each) forms four separate shorts (16 bit each). That means the actual memory can remain untouched, just the container has to change.

Already know that I can achieve this by memcopying into a new array:

std::vector<unsigned short> shorts_vec(long_long_vec.size()*4);
std::memcpy(&shorts_vec[0], &long_long_vec[0], sizeof(unsigned long long int) * long_long_vec.size());

But I wonder whether there is an in-place solution that does not require copying.

DragonGamer
  • 834
  • 3
  • 9
  • 27
  • Not without diving into undefined behaviour. [Strict Aliasing](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) has been broken. – user4581301 Nov 14 '19 at 23:05
  • There is no way to do it. (`memcpy`ing the vector *itself* (not its contents) into a vector of different type may or may not work if done carefully, but it's UB). – HolyBlackCat Nov 14 '19 at 23:06
  • Note that C++ only guarantees minimum sizes, not actual sizes. If you wan a guaranteed 64 or 16 bit number, you will need to use a `_t` style number. –  Nov 14 '19 at 23:13
  • Chipster is referring to [Fixed Width Integers](https://en.cppreference.com/w/cpp/types/integer). – user4581301 Nov 14 '19 at 23:25
  • Do the benchmarking (which you say you haven't done) before worrying about accesssing a vector of `unsigned long long` as if it is a vector of `unsigned short`. Your approach is called premature optimisation for a reason. Humans tend to be very BAD at identifying optimisation opportunities when they haven't conducted measurements/profiling and very OVER-CONFIDENT in their own ability to optimise their code. – Peter Nov 15 '19 at 01:18
  • Beginning with C++20 you can use [`std::bit_cast`](https://en.cppreference.com/w/cpp/numeric/bit_cast). Note that you then should probably not cast the vectors themselves but the pointers to the underlying arrays (accessible by [`std::vector::data()`](https://en.cppreference.com/w/cpp/container/vector/data)) – n314159 Nov 15 '19 at 01:51
  • Does it have to be a vector? – Red.Wave Nov 15 '19 at 07:56

0 Answers0