Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cast vector<int> to vector<unsigned int>

I have a vector<int> and functions that only accepts a vector<unsigned int> references.I know that I could change/template the functions(and this is likely the best thing to do), but ideally I would have a way to cast/convert the vector<unsigned int> reference to a vector<int> reference. I know that all values in the vector are positive, and non of the functions will even come close to overflowing the intigers.

I have tried using static_cast<vector<int>> but that doesnt work.

Edit:
I say cast/convert of the references but I am not looking to create a new copy and reference that.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There is no cast that does not result in undefined behaviour, but if you really want to do this then this will probably work in practise

*reinterpret_cast<vector<unsigned int>*>(&vec)

Create a pointer, cast the pointer, then dereference. I used to do this sort of thing all the time when I was a C programmer.

Really though, you should not do this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading