Click here to Skip to main content
15,892,643 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

C#
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


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.
Posted
Updated 8-Jun-16 11:33am
Comments
barneyman 7-Jun-16 19:43pm    
you don't have an exit condition ... it'll find 3 fives, then it won't find any - so it'll return .end() - which you then try to increment

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


Try
C++
#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;

}
 
Share this answer
 
Comments
shivam gohel 9-Jun-16 3:19am    
perfect!
thank you sir!
you have always been helpful to me...
CPallini 9-Jun-16 3:36am    
You are welcome.
you are using the iterator wrong. You add 1 (bit) to it and NOT the full size.

It should be:
C++
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 ;-)
 
Share this answer
 
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:

C++
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;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900