MST

星途 面试题库

面试题:C++ STL自定义容器适配begin迭代器

假设你需要自定义一个类似链表的容器MyList,要求实现begin()迭代器以适配STL算法。请写出MyList类的大致框架,并实现begin()函数,同时说明如何确保该迭代器满足STL对迭代器的要求。
26.2万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>

// 定义链表节点
template <typename T>
struct MyListNode {
    T data;
    MyListNode* next;
    MyListNode(const T& value) : data(value), next(nullptr) {}
};

// 定义MyList迭代器
template <typename T>
class MyListIterator {
public:
    using iterator_category = std::forward_iterator_tag;
    using value_type = T;
    using difference_type = std::ptrdiff_t;
    using pointer = T*;
    using reference = T&;

    MyListIterator(MyListNode<T>* node) : current(node) {}

    T& operator*() const {
        return current->data;
    }

    T* operator->() const {
        return &(current->data);
    }

    MyListIterator& operator++() {
        current = current->next;
        return *this;
    }

    MyListIterator operator++(int) {
        MyListIterator temp = *this;
        ++(*this);
        return temp;
    }

    bool operator==(const MyListIterator& other) const {
        return current == other.current;
    }

    bool operator!=(const MyListIterator& other) const {
        return!(*this == other);
    }

private:
    MyListNode<T>* current;
};

// 定义MyList类
template <typename T>
class MyList {
public:
    MyList() : head(nullptr) {}

    ~MyList() {
        while (head) {
            MyListNode<T>* temp = head;
            head = head->next;
            delete temp;
        }
    }

    void push_back(const T& value) {
        if (!head) {
            head = new MyListNode<T>(value);
        } else {
            MyListNode<T>* current = head;
            while (current->next) {
                current = current->next;
            }
            current->next = new MyListNode<T>(value);
        }
    }

    MyListIterator<T> begin() {
        return MyListIterator<T>(head);
    }

private:
    MyListNode<T>* head;
};

确保迭代器满足STL要求的说明

  1. 迭代器类别:定义了iterator_categorystd::forward_iterator_tag,表明这是一个前向迭代器,满足STL对前向迭代器的基本要求,支持++操作来移动到下一个元素。
  2. 类型定义:定义了value_typedifference_typepointerreference,这些类型定义是STL算法使用迭代器时所需要的,保证了与STL算法的兼容性。
  3. 解引用操作:实现了operator*operator->,使得可以通过迭代器访问节点中的数据。
  4. 自增操作:实现了前置++和后置++操作符,用于移动迭代器到下一个节点。
  5. 比较操作:实现了operator==operator!=,用于比较两个迭代器是否相等,这在STL算法中用于判断迭代器是否到达末尾等情况。