C++ 如何将find_if与链表等非容器一起使用?

C++ 如何将find_if与链表等非容器一起使用?,c++,algorithm,c++11,linked-list,iterator,C++,Algorithm,C++11,Linked List,Iterator,我正在尝试为静态对象列表提供算法支持。我尝试过各种方法,但我能让它工作的唯一方法是编写一个传统的C for循环 例如: class ListNode { public: ListNode(int id); virtual ~ListNode() {} // Container support functions ListNode* operator++() {return m_nextNode;} static ListNode* findNode(in

我正在尝试为静态对象列表提供算法支持。我尝试过各种方法,但我能让它工作的唯一方法是编写一个传统的C for循环

例如:

class ListNode
{
public:
    ListNode(int id);
    virtual ~ListNode() {}

    // Container support functions
    ListNode* operator++() {return m_nextNode;}
    static ListNode* findNode(int p_id);
    static ListNode* m_nodeList{nullptr};

private:
    int m_id;
    ListNode *m_nextNode;

protected:
    static void addNewNode(ListNode* p_node);

    friend ListNode* begin(void);
};

inline ListNode* begin(void) {return ListNode::m_nodeList;}
inline ListNode* end(void) {return nullptr;}

// Declare the list head
ListNode* ListNode::m_nodeList = nullptr;

// Constructor
ListNode::ListNode (int id): m_id{id}
{
    ListNode::addNewNode(this);
}

// Add node to front of list
void ListNode::addNewNode(ListNode* p_node)
{
    p_node->m_nextService = m_nodeList;
    m_nodeList = p_node;
}

//
// The following are all the find implementation attempts
//

ListNode* ListNode::failedFind1(int id) {
   return std::find_if(ListNode::m_nodeList,
      static_cast<ListNode*>(nullptr),
      [p_serviceNumber](const ListNode& s) {
         return id==s.m_id;
      }
);

我遗漏了什么?

谢谢您的反馈

我为安全关键应用程序开发软件。通常不允许使用动态内存。STL链表类是一个独立的数据结构,用于维护对象列表。我们有对象,只需要它们作为STL兼容的容器对象运行。(这就是原因)


这是非常有用的。问题是增量运算符的定义有误。

问题是
开始
/
结束
函数返回一个指针,因此当
find\u if
++
递增指针时,它只会递增指针,指向第一个节点后的垃圾,并且不使用
运算符+++


您需要定义一个迭代器类对象,它同时定义(一元)
operator*
operator++
,并让begin/end返回该对象。这个迭代器类可能只包含一个指针字段。

查看调试器的问题,我发现了这一点。将ListNode*定义为迭代器,STL将其解释为随机访问迭代器,而不是前向迭代器。在这种情况下,begin()和end()应该是指向数组的指针,在数组中可以减去它们来确定关系。由于end()被定义为nullptr,因此find_if()算法没有执行递增运算符并立即中止,返回end()


<> p>所以我需要知道如何定义一个转发C++,以便列表遍历工作正常。

您错过了关于构建C++容器和迭代器的所有内容。我不知道我在哪里读到它的规则,但试试Stroustrup的C++书。也可以阅读C++标准库中的代码。当然,已经存在的一个已经链接的链表容器已经被使用了。为什么要尝试构建自己的链表类?了解数据结构。在例如boost中有一些侵入性的链表实现,你可能应该研究一下。忘记了在原始帖子中提到操作符++()。这就是我现在拥有的。
//容器支持函数typedef AbstractService*迭代器;typedef const AbstractService*常量迭代器;静态迭代器begin()noexcept{return iterator(AbstractService::m_serviceList);}静态迭代器end()noexcept{return iterator(nullptr);}迭代器和运算符++(){return m_nextService;}
不起作用,因为
++
已经为指针类型定义了,不能重载--只能重载类类型上的运算符,不在“内置”类型上。因此,您需要迭代器类型是类类型,而不是指针类型。指针仅用作原始数组的迭代器。
for (auto *s = m_nodeList; s != nullptr; s = s->m_nextNode)
{
    if (s->m_id == id)
        return s;
}
return nullptr;