Must size() == end() - begin()? What about the cast?

后端 未结 2 1152
面向向阳花
面向向阳花 2021-02-12 14:58

From what I understand, the purpose of size_type and difference_type is not merely the sign -- it was also meant to address e.g. segme

2条回答
  •  [愿得一人]
    2021-02-12 15:28

    Here's what the C++11 standard has to say on various things here:

    § 23.2.1

    Expression: difference_type
    Return Type: signed integer type
    Operational Semantics: -
    Assertion/note, pre-/post-condition: is identical to the difference type of iterator and const_iterator
    Complexity: compile-time
    
    Expression: size_type
    Return Type: unsigned integer type
    Operational Semantics: -
    Assertion/note, pre-/post-condition: size_type can represent any non-negative value of difference_type
    Complexity: compile-time
    
    Expression: size()
    Return Type: size_type
    Operational Semantics: distance(begin(),end()) 
    Assertion/note, pre-/post-condition: -
    Complexity: constant
    

    Let's make sure size() is equivalent to end() - begin():

    § 24.4.4/4

    distance():
    Effects: If InputIterator meets the requirements of random access iterator, 
    returns (last - first); otherwise, returns the number of increments needed 
    to get from first to last
    

    Since your container has random-access iterators, this holds true. That's that. As you can see in the first box,

    size_type can represent any non-negative value of difference_type
    

    From that, we have that the cast from difference_type to size_type should be valid for all non-negative values.

提交回复
热议问题