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

Converting difference_type to int.

27 views
Skip to first unread message

Paul

unread,
May 9, 2016, 5:18:30 AM5/9/16
to
The following (incomplete) code compiles fine and runs as expected when obvious modifications are made. However, I haven't found anything explicitly saying that it's ok to do this. How can I be sure there's no issue with converting set<int>::difference_type to int?
Thanks,

Paul

std::set<int> x{5,3};
int y = std::distance(x.begin(), x.find(5));
std::cout << y;

Ben Bacarisse

unread,
May 9, 2016, 6:31:47 AM5/9/16
to
Paul <peps...@gmail.com> writes:

> The following (incomplete) code compiles fine and runs as expected
> when obvious modifications are made.

I get a warning that converting to int may alter the value (the two
types are different sizes on my system).

> However, I haven't found
> anything explicitly saying that it's ok to do this. How can I be sure
> there's no issue with converting set<int>::difference_type to int?
>
> std::set<int> x{5,3};
> int y = std::distance(x.begin(), x.find(5));
> std::cout << y;

I don't think there is one. You could hope that a compiler will tell
you and the everyone using your code will pay heed to and such messages.
Or you could check the size or, more accurately, the range of the two
types but that would be very fussy. What's wrong with using the right
type off the bat:

std::set<int> x{5,3};
auto y = std::distance(x.begin(), x.find(5));
std::cout << y;

?

--
Ben.
0 new messages