到达向量中我们选择的最后一个元素

到达向量中我们选择的最后一个元素

本文介绍了使用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.

推荐答案

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;

}


iter++;//incrementing the iterator



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



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


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

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


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()到达向量中我们选择的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:56