How can I find a specific variable in a <Object *> vector in C ++?

I am new to vector in C ++ and I use a pointer in it. I would like to find a variable if it already exists in the vector, but I'm not sure how to do it.

B.cpp

vector<Animal*> vec_Animal; vector<Animal*>::iterator ite_Animal; 

What I'm trying to compare is Animal->getID();

And I have one more question. Is there a way to make a limit when a user enters a value? I mean, if there is a year value, then I want it to be printed only 1000 ~ 2011. If the user puts 999, it will be wrong. Is it possible?

Greetings

+4
source share
2 answers

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.

+3
source

You can simply navigate the vector by index, gaining access to the element identifier property and comparing it with yours. There are several different ways to do this at http://setoreaustralia.com/ZpdHMFATCphM4Xz.php , which are designed to search for an item based on a number of properties

0
source

All Articles