【发布时间】:2020-09-08 05:57:59
【问题描述】:
如果 v 向量及其对应的索引中存在数字“h”,则代码的目的是打印“是”。如果该数字不存在,您必须打印“No”,然后打印比该数字大的下一个最小数字的索引。
提前感谢您的帮助。
//Code (1) .
cin >> h;
int lower = lower_bound(v.begin(),v.end(),h);
if(v[lower] == h) cout<<"Yes ";
else cout<<"No ";
cout << lower+1;
通过code(1)产生上述错误,但是当我们使用code(2)时程序运行成功。
//Code (2).
cin >> h;
int lower = lower_bound(v.begin(),v.end(),h) - v.begin();
if(v[lower] == h) cout<<"Yes ";
else cout<<"No ";
cout << lower+1;
cout<<endl;
当我们减去 v.begin() 时会发生什么不同。
【问题讨论】:
-
查看
lower_bound返回的内容。如果您不知道在哪里查找,那么您可以在这里查找:en.cppreference.com/w -
@NathanOliver i 我提到了几个网站,但是,当显示我们总是用来减去 v.begin 的下限时,我没有从中得到原因。如果你能轻描淡写这个概念,那就太好了。谢谢
-
en.cppreference.com/w/cpp/algorithm/lower_bound - 看看它返回了什么; 迭代器.
-
@Jesper Juhl Yeh,我知道它返回迭代器,并且由于 'v.begin()' 也是一个迭代器,请帮助我了解当我们用另一个迭代器减去一个迭代器时会发生什么不同(lower_bound 返回的迭代器- v.begin())
-
考虑边缘情况,例如空容器和
end()的返回。另请阅读UB。
标签: c++ pointers vector stl iterator