How do I find elements with custom comparators with std::vector in multithreaded code?

In C++, when working with multithreaded code, finding elements in a `std::vector` using custom comparators can be achieved using algorithms from the Standard Template Library (STL). However, care must be taken to ensure thread safety when accessing shared data structures like vectors. Below is an example demonstrating how to find elements with a custom comparator in a multithreaded environment.

Keywords: C++, std::vector, custom comparators, multithreading, thread safety, STL
Description: This guide provides an example of how to efficiently find elements in a std::vector using custom comparators in a multithreaded C++ application while ensuring thread safety.
#include <iostream> #include <vector> #include <algorithm> #include <thread> #include <mutex> // Custom comparator struct CustomComparator { bool operator()(const int &a, const int &b) const { return a < b; // Define your custom comparison logic here } }; // Function to find an element void findElement(const std::vector<int> &vec, int target, std::mutex &m) { std::lock_guard<std::mutex> lock(m); // Ensuring thread safety auto it = std::find_if(vec.begin(), vec.end(), [target](const int &value) { return value == target; // Modify as per your search condition }); if (it != vec.end()) { std::cout << "Element " << target << " found!" << std::endl; } else { std::cout << "Element " << target << " not found." << std::endl; } } int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; std::mutex m; // Creating threads to find elements std::thread t1(findElement, std::ref(vec), 3, std::ref(m)); std::thread t2(findElement, std::ref(vec), 6, std::ref(m)); t1.join(); t2.join(); return 0; }

Keywords: C++ std::vector custom comparators multithreading thread safety STL