c++ - Stop Code instead of break with a Error Message -
here code great website want quite (searching in vector of class objects addressing class objects).
#include <iostream> #include <vector> #include <functional> #include <algorithm> using namespacestd; class class1 { private: int id; double value; public: class1(int i, double v) :id(i), value(v){ } int getid()const { return id; } double getvalue() const { return value; } }; class hasidentifier :public unary_function<class1, bool> { public: hasidentifier(int id) : m_id(id) { } bool operator()(const class1& c)const { return (c.getid() == m_id); } private: int m_id; }; class class2 { private: vector <class1> objects; public: class2() { objects.push_back(class1(1, 100.0)); objects.push_back(class1(2, 100.0)); objects.push_back(class1(3, 100.0)); } double getvalueofid(int id) { vector<class1>::iterator itelem = find_if(objects.begin(), objects.end(), hasidentifier(id)); return itelem->getvalue(); } }; int main() { class2 c; int id = 4; cout << id << " " << c.getvalueofid(id); cin.get(); return 0; } it works whenenver put "int id ">3 crashes because object has size 3. got this, there possibility warned when happen not crash im able correct somehow in code warn message?
you should check returned iterator validness , throw , exception (or report error other way) if invalid:
if (itelem == objects.end()) throw myverycoolexception("woops wrong id"); dont forget set global exception handler (toplevel catch), otherwise application still crash if exception uncaught.
Comments
Post a Comment