0

iterator1 and iterator2 are two pointers of a structure.

I know that size_t(iterator1 - iterator2) is to get the length. But how can we use size_t like that? Is that similar to the forced type conversion like (size_t)(iterator1 - iterator2)?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
Ivy
  • 21
  • 4

1 Answers1

3

Your syntax is merely an instruction to create a size_t based on the value of the expression iterator1 - iterator2.

size_t is not the best type for this (as it's unsigned), and neither is the method taken the best approach.

Assuming that iterator1 and iterator2 are iterators on the same container (otherwise the behaviour of what I present and what you have is undefined),

auto diff = std::distance(iterator1, iterator2);

is to be preferred.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    I rather suspect that the only reason you would cast the result to a `size_t` like this is if you needed the result to be a `size_t` which would make it the best type for this. Although some test to ensure data is not corrupted would be appropriate. – Galik Feb 12 '19 at 19:45