I have repeating code in my work, and I want to get rid of it, so I know that in C++ it is not good idea to use macro, but instead I must use inline function, is it good idea to use this function as inline:
list<Data>::iterator foo(int data){
if(dataExists(data)){
list<Data>::iterator i;
for(i = dataClass.begin(); i != dataClass.end(); ++i){
if(i->getData() == data){
break;
}
return i; //here I have one more problem, what can I return if data doesn't exist?
}
I think that this function is very unsafe. How can I improve my code?
What you're doing here is already done by the std::find()
function, so it would be better to use that (although it's certainly OK to try implementing these things yourself for the exercise).
std::find()
also demonstrates a good way to indicate the "not found" condition -- if the item is not found, it returns the iterator one-past-the-end. That way, the caller can determine whether a matching item was found by comparing the iterator returned with Data.end()
.