如何避免重复代码?

hel*_*rld 0 c++ inline-method

我有一些技术问题,我在工作中重复了代码,我想摆脱它,所以我知道在C++中使用宏不是一个好主意,而是我必须使用内联函数,这是个好主意将此函数用作内联:

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?
}
Run Code Online (Sandbox Code Playgroud)

我是初学者,我认为这个功能非常不安全,有人可以给我建议,我怎样才能改进我的代码,提前谢谢

PS通常用什么来避免重复代码?

我编辑了代码

j_r*_*ker 8

你在这里做的事情已经由std::find()函数完成,所以最好使用它(尽管你自己尝试实现这些东西当然可以).

std::find()还演示了指示"未找到"条件的好方法 - 如果找不到该项,则返回迭代器一个接一个的结束.这样,调用者可以通过比较返回的迭代器来确定是否找到了匹配项Data.end().

  • 不,没有`std :: list <T> :: find()`.但是你可以使用`std :: find()`:`std :: find(myList.begin(),myList.end(),dataToFind)`.见http://www.cppreference.com/wiki/stl/algorithm/find (6认同)
  • +1,但在这种特殊情况下,您需要将`find_if`与谓词一起使用,该谓词测试成员函数返回的值与您要查找的值的相等性... (2认同)