且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用find()到达向量中我们选择的最后一个元素

更新时间:2023-11-10 08:01:04

怎么样呢

What about
auto iter = find( a.rbegin(), a.rend(), 5);







试试

?


Try

#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;

int main()
{
  vector<int>a = {5,1,2,3,5,4,5,6 };

  auto iter = find( a.rbegin(), a.rend(), 5);

  if ( (iter != a.rend())) std::cout << "found at position " << (a.rend() - iter- 1 ) << endl;

}


您使用的迭代器错误。你加1(位)而不是全尺寸。



它应该是:

you are using the iterator wrong. You add 1 (bit) to it and NOT the full size.

It should be:
iter++;//incrementing the iterator



看看 cplpusplus 是如何做到的并起诉调试器。



提示:阅读一些文档并搜索示例代码; - )


Take a look how cplpusplus is doing it and sue a debugger.

Tip: Read some documentation and search for example code ;-)


你得到的错误很容易解释:在循环的第四次迭代中,iter指向序列中的最后一个元素(6),find将失败,因此返回a.end()。所以ptr现在具有a.end()的值。在下一个语句中,您尝试增加ptr并且失败,因为ptr + 1将超出范围。这正是错误消息试图告诉你的。



您可以使用CPallini建议的反向查找,或者,如果您想要挽救您的方法,请编写它像这样:



The error you are getting is quite easy to explain: In the fourth iteration of your loop iter points to the last element in the sequence (the 6) and find will fail, so it returns a.end(). So ptr now has the value of a.end(). In the next statement you try to increment ptr and that fails, because ptr + 1 would be out of range. That's exactly what the error message is trying to tell you.

You may either use a reverse find as CPallini suggests or, if you want to salvage your approach, write it like this:

auto iter = a.begin();
while (true) {
    auto ptr = find(iter, a.end(), 5);
    if (ptr == a.end())
        break; // not found, so break out and leave iter on the last found value
    iter = ptr + 1;
}