Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Is there a way to cast from vector<unsigned> to vector<int>?

40 views
Skip to first unread message

Peng Yu

unread,
Jun 7, 2015, 11:39:23 PM6/7/15
to
Suppose that I have a variable of vector<unsigned>, and a function that takes an argument of const vector<int>&.

One thing to pass this variable to this function is to create a copy (with type vector<int>) of the variable, but this involes the extra copying.

Is there a way to somehow directly supply the variable to the function without using a copy?

Regards,
Peng
Message has been deleted

Richard

unread,
Jun 8, 2015, 2:05:11 PM6/8/15
to
[Please do not mail me a copy of your followup]

Peng Yu <peng...@gmail.com> spake the secret code
<57513843-102e-4199...@googlegroups.com> thusly:

>Is there a way to somehow directly supply the variable to the function
>without using a copy?

No. An unsigned can hold positive integer values that don't fit into
an int.
--
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
The Computer Graphics Museum <http://computergraphicsmuseum.org>
The Terminals Wiki <http://terminals.classiccmp.org>
Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>

Mr Flibble

unread,
Jun 8, 2015, 2:12:42 PM6/8/15
to
On 08/06/2015 04:58, Stefan Ram wrote:
> Peng Yu <peng...@gmail.com> writes:
>> Suppose that I have a variable of vector<unsigned>, and a
>> function that takes an argument of const vector<int>&.
>> Is there a way to somehow directly supply the variable to the
>> function without using a copy?
>
> You can cast the object, but this might mean that the cast
> or call will have undefined behaviour or in the best case
> will behave as if each unsigned was reinterpret as an int.
>
> Under some implementations this might be acceptable when all
> the unsigned objects have values that can be represented as
> an int.
>
> For example, one implementation gave:
>
> #include <iostream>
> #include <ostream>
> #include <vector>
> #include <climits>
>
> int main()
> { ::std::vector< unsigned >v{ 0, 1, INT_MAX,( unsigned )INT_MAX +( unsigned )1 };
> for( unsigned u : v )::std::cout << u << '\n';
> auto const &w( *reinterpret_cast< ::std::vector< int >* >( &v ) );
> for( int i : w )::std::cout << i << '\n'; }
>
> 0
> 1
> 2147483647
> 2147483648
> 0
> 1
> 2147483647
> -2147483648

You know it is UB yet you still suggest it? It is never acceptable to
deliberately invoke UB. Mate, I am sorry but if you wrote such code for
me you would be fired.

/Flibble
0 new messages