Horje
How to Find the Last Element in Vector Which Satisfies a Condition?

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++

// C++ program to illustrate how to find the last element in
// vector which satisfies the given condition
#include <algorithm>
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initialize a vector
    vector<int> myVector = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  
    // Use reverse iterator to find the last even number
    auto it = find_if(myVector.rbegin(), myVector.rend(),
                      [](int num) { return num % 2 == 0; });
  
    // checking if we found the element or not
    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)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Remove an Element from Vector in C++? How to Remove an Element from Vector in C++?
How to Replace All Occurrences of an Element in a Vector in C++? How to Replace All Occurrences of an Element in a Vector in C++?
How to Find Second to Last Element in a Vector in C++? How to Find Second to Last Element in a Vector in C++?
How to Insert a Pair into an Unordered Map in C++? How to Insert a Pair into an Unordered Map in C++?
How to Handle Incorrect Values in a Constructor? How to Handle Incorrect Values in a Constructor?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13