i + 1 <vec.size()和i <vec.size()-1之间的差异

时间:2019-06-26 11:45:27

标签: c++ runtime-error size

在编程时,我发现我在使用条件i + 1< vec.size()时代码给出了运行时错误,但在vec上运行正常。 这里std::vector是空的//giving error vector<int> vec; for (int i = 0; i < vec.size() - 1; i++) { //some code } //not giving error vector<int> vec; for (int i = 0; i + 1 < vec.size(); i++) { //some code }

Inductive nostutter {X:Type} : list X -> Prop :=
| ns_nil : nostutter []
| ns_one : forall (x : X), nostutter [x]
| ns_cons: forall (x : X) (h : X) (t : list X), nostutter (h::t) -> x <> h -> nostutter (x::h::t).

Example test_nostutter_4:      not (nostutter [3;1;1;4]).
Proof.
  intro.
  repeat match goal with
    h: nostutter _ |- _ => inversion h; clear h; subst
         end.
  contradiction.
Qed.

2 个答案:

答案 0 :(得分:13)

方法std::vector::size返回一个未签名的std::size_t。因此,如果为空,您将得到0 - 1,但表示为无符号数字,该数字将下溢并根据two's complement变为18446744073709551615

答案 1 :(得分:4)

侧注。比较有符号和无符号数字不是一个好主意。在C ++ 20中,我们将有一个新函数std::ssize,该函数返回带符号的类型。然后您的示例写为

 for (std::ptrdiff_t i = 0; i < std::ssize(vec) - 1; ++i)
 {
     //some code
 }

将完全有效。

还要注意如何将i声明为std::ptrdiff_t(带符号整数类型)以指示数组索引。

相关问题