How to Find the Last Element in Vector Which Satisfies a Condition?
Last Updated :
13 Feb, 2024
In C++, vectors are dynamic containers with the ability to resize themselves automatically when an element is inserted or deleted. In this article, we will learn how to find the last element in a vector that satisfies the given condition in C++.
Example
Input:
myVector ={10, 20, 40, 20, 50, 10, 20, 30}
Output:
Element present at index: 6
Find the Last Element in Vector Which Satisfies a Condition
To find the last element in a vector that satisfies the given condition, we can use the std::find_if() method provided by the STL library in C++. This method will return the iterator to the matching element. We then use the std::distance() to calculate the actual index value.
C++ Program to Find the Last Element in Vector Which Satisfies a Condition
In this example, we will find the last even number in the vector container as an example.
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > myVector = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
auto it = find_if(myVector.rbegin(), myVector.rend(),
[]( int num) { return num % 2 == 0; });
if (it != myVector.rend()) {
cout << "The last even number in the vector is at: "
<< distance(it, myVector.rend()) - 1 << "\n" ;
}
else {
cout << "No even numbers found in the vector.\n" ;
}
return 0;
}
|
Output
The last even number in the vector is at: 7
Time Complexity: O(N), where N is the total number of elements present in the vector.
Auxilary Space: O(1)
Share your thoughts in the comments
Please Login to comment...