user11910061
user11910061

Reputation:

C++ Find Algorithm: How do I find the last occurance of an element?

I'd like to find the last element of an array that satisfies a given condition. In return I'd like either:

  1. An iterator, such that I can use std::distance to find the distance between that iterator and the beginning of the vector, or

  2. Directly have the position of said element returned.

In general, what I'm trying to solve is: (i) Find the maximum element in the vector (max_element), and (ii), find the first occurrence of 0 before that max element.

So in the following example:

{0, 10, 20, 0, 5, 50, 0, 70, 10, 0} 
// Get max at position 7, return 0 at position 6

After using max_element from the algorithm header, I tried something like the below code snippet using reverse iterators.

auto Itr1 = std::max_element(vect.begin(), vect.end());
auto Itr2 = std::find(Itr1, vect.rend(), [](int i){return i == 0;});

Mixing reverse and forward iterators wasn't fun and didn't work. It seems like there should be a more elegant solution.

Upvotes: 0

Views: 1132

Answers (3)

Eyal K.
Eyal K.

Reputation: 1072

This works, not very elegant though, requires another vector that only has 0 in it:

std::vector<int> v1 { 0, 10, 20, 0, 5, 50, 0, 70, 10, 0 };
std::vector<int> v2 { 0 };

auto Itr1 = std::max_element(v1.begin(), v1.end());
auto Itr2 = std::find_end(v1.begin(), Itr1, v2.begin(), v2.end());

Upvotes: 0

srt1104
srt1104

Reputation: 959

You can make use of make_reverse_iterator() defined in header <iterator>. Also note that the third argument which find() takes is value which is to be found.

    std::vector<int> A{ 0, 10, 20, 0, 5, 50, 0, 70, 10, 0 };
    auto itr1 = std::max_element(A.begin(), A.end());
    auto itr2 = std::find(std::make_reverse_iterator(itr1), A.rend(), 0);

Upvotes: 1

kishoredbn
kishoredbn

Reputation: 2097

Got wrong at first, I think you are looking for reverse_iterator

int main()
{

  std::vector<int> vect{0, 10, 20, 0, 5, 50, 0, 70, 10, 0};
  auto Itr1 = std::max_element(vect.begin(), vect.end());
  auto Itr2 = find_if(std::make_reverse_iterator(Itr1), vect.rend(), [](int i){return i == 0;});

  std::cout<< vect.rend() - Itr2 - 1<<std::endl;
  return 0;

}

Upvotes: 0

Related Questions