You can use the std :: find_if algorithm .
Perhaps you are using std::vector::push_back or such methods to populate the vector. These methods do not provide any checks, but one way to achieve this is to write a small wrapper function inside which you check the valid conditions of the data, and if the data is good, then you add this to the vector, otherwise you just return some error or throw a std::out_of_range exception std::out_of_range from your wrapper function.
Online demo
Here is an example of minimalistic code, of course, you will need to customize it even more to suit your needs:
#include<iostream> #include<vector> #include<algorithm> using namespace std; class Animal { public: int id; }; class Ispresent { public: int m_i; Ispresent(int i):m_i(i){} bool operator()(Animal *ptr) { cout<<"\n\nInside IsPresent:"<<ptr->id; return (ptr->id == m_i); } }; int main() { vector<Animal*> vec_Animal; Animal *ptr = new Animal(); ptr->id = 10; vec_Animal.push_back(ptr); Animal *ptr1 = new Animal(); ptr1->id = 20; vec_Animal.push_back(ptr1); Animal *ptr2 = new Animal(); ptr2->id = 30; vec_Animal.push_back(ptr2); vector<Animal*>::iterator ite_Animal = vec_Animal.begin(); for(ite_Animal; ite_Animal != vec_Animal.end(); ++ite_Animal) cout<<"\nVector contains:"<< (*ite_Animal)->id; vector<Animal*>::iterator ite_search; /*Find a value*/ ite_search = std::find_if( vec_Animal.begin(), vec_Animal.end(), Ispresent(20)); if(ite_search != vec_Animal.end()) cout<<"\n\nElement Found:"<<(*ite_search)->id; else cout<<"\n\nElement Not Found"; return 0; }
Please note that the sample is just an example of how to work with find_if , it does not correspond to the best methods.
source share