开发者

Can std::find function use for our own classes?

I have set of classes. Each class is inherited from another class. The relationship is as follows. (I am just posting开发者_如何转开发 how one class inherited from another class, just to get idea for all of you)

class LineNumberList : public MyVector <LineNumber > //top class
class MyVector : public std::vector <Type>
class LineNumber : public ElementNumber 

class ElementNumber {                 //this is the base class
        protected:
    int number;
        public:
    ElementNumber(int p){number=p;}
         // some more codes // 
}

Now, I want to implement a function which can be used to find elements inside my topclass i.e. LineNumberList. I tried with standard find function, but it doesn’t work. Can anyone help me to implement similar find function for my case, it is highly appreciated.


"I tried with standard find function, but it doesn’t work." Works for me:

#include <vector>
#include <iostream>
#include <algorithm>

class ElementNumber {
  protected:
    int number;
  public:
    ElementNumber(int p) :number(p) {}
    bool operator==(const ElementNumber&e) { return number == e.number; }
};
class LineNumber : public ElementNumber {
  public:
    LineNumber(int p) : ElementNumber(p) {}
};
template <class Type>
class MyVector : public std::vector<Type> {
};
class LineNumberList : public MyVector<LineNumber> {
};

// EDIT: add local implementation of std::find
template<class InputIterator, class T>
InputIterator myfind ( InputIterator first, InputIterator last, const T& value )
{
  http://www.cplusplus.com/reference/algorithm/find/
  for ( ;first!=last; first++) if ( *first==value ) break;
  return first;
}

int main() {
  LineNumberList ll;
  LineNumber l(7);
  ll.push_back(l);
  std::cout << std::boolalpha << !(std::find(ll.begin(), ll.end(), l) == ll.end()) << "\n";
  std::cout << std::boolalpha << !(::myfind(ll.begin(), ll.end(), l) == ll.end()) << "\n";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜