find a member variable in a vector of objects cpp

#include <iostream>
#include <vector>
#include <algorithm>

class MyClass {
public:
    int memberVariable;

    MyClass(int value) : memberVariable(value) {}
};

int findMemberVariable(const std::vector<MyClass>& myObjects, int targetValue) {
    auto it = std::find_if(myObjects.begin(), myObjects.end(),
                           [targetValue](const MyClass& obj) {
                               return obj.memberVariable == targetValue;
                           });

    if (it != myObjects.end()) {
        return it->memberVariable;
    } else {
        // Handle the case when the member variable is not found in the vector
        return -1; // or any suitable default value
    }
}

int main() {
    // Create a vector of MyClass objects
    std::vector<MyClass> myObjects = {MyClass(10), MyClass(20), MyClass(30), MyClass(40)};

    // Specify the target value to find
    int targetValue = 30;

    // Find the member variable in the vector
    int result = findMemberVariable(myObjects, targetValue);

    // Print the result
    std::cout << "Member variable found: " << result << std::endl;

    return 0;
}