使用find()到达向量中我们选择的最后一个元素 [英] Reaching the last element of our choice in the vector using find()

查看:689
本文介绍了使用find()到达向量中我们选择的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是在下面的代码中注释。

作为find给出一个指向找到的第一个值的迭代器..我想达到我想要的给定向量中的最后一个值选择使用查找功能。

谢谢。



what i want to do is commented in the code below.
as find gives an iterator pointing to the first value found.. i want to reach the last value in my given vector of my desired choice using find function.
Thanks.

vector<int>a = {5,1,2,3,5,4,5,6 };
	//i want to make my iterator iter point to the second last "5" in the given vector  i.e a[6].
	auto iter = a.begin();
	do {
		auto ptr = find(iter, a.end(), 5);
		iter = ptr + 1;			
	} while (iter != a.end());
	// error shown is vector iterator + offset out of range and the program crashes





我的尝试:



i havent尝试了什么特别的但也许迭代器的添加肯定会有一些问题。



一个可能的解决方案是或者iter = ptr + 1;使用iter = iter + 1;

但这可能会增加时间复杂度,这不是我问题的完美解决方案。



What I have tried:

i havent tried anything special. but maybe there must be some problems with the iterators addition.

one possible solution is instead or iter=ptr+1; use iter=iter+1;
but this may increase the time complexity and this is not the perfect solution to my question.

推荐答案

怎么样呢

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;
}


这篇关于使用find()到达向量中我们选择的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆