Range type in c++

学弟的一个问题让我发现了自己的一个知识盲区

问题:

统计字符串中的字母,数字,符号的个数,并删除数字

联想:

问题本身是很简单的,但c++的range type 迭代怎么实现
即怎么让自己写的类可以这样迭代: for(type foo: list)
关键在于实现begin,end方法,返回一个对象(称之为iterator)
然后iterator中要实现!= * ++方法即可

运用range type,有下面简单实现:

main.cpp
#include <iostream>
#include "LinkedList.h"

using namespace std;
LinkedList<char> l;
int digit = 0, letter = 0, others = 0;

void input() {
    char c;
    while (true) {
        c = getchar();
        if (c == '\n' || c == EOF)
            break;
        if (c >= '0' && c <= '9') {
            ++digit;
        } else {
            l.push_back(c);
            if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
                letter++;
            } else others++;
        }
    }
}

int main() {
    input();
    cout << letter << ' ' << digit << ' ' << others << endl;
    for (char c:l)
        cout << c;
    cout << endl;
    return 0;
}
LinkedList.h
//
// Created by ngkimbing on 10/4/19.
//

#ifndef ACM_LINKEDLIST_H
#define ACM_LINKEDLIST_H


template<typename T>
class Node {
public:
    T val;
    Node *next;

    Node() : next(NULL) {}

    Node(T val, Node *next = NULL) : val(val), next(next) {}

};

template<typename T>
class LinkedList {
private:
    class Iterator {
    private:
        Node<T> *p;
    public:
        explicit Iterator(Node<T> *p) : p(p) {}

        const Iterator &operator++() {
            p = p->next;
            return *this;
        }

        bool operator==(const Iterator &rhs) const {
            return p == rhs.p;
        }

        bool operator!=(const Iterator &rhs) const {
            return !(rhs == *this);
        }

        T operator*() const {
            return p->next->val;
        }
    };

    Node<T> *head;
    Node<T> *tail;
    int size;
public:
//    explicit LinkedList(Node<T> *head);

    LinkedList();

    Iterator begin();

    Iterator end();

    void push_back(T ele);

};

#include "LinkedList.cpp"

#endif //ACM_LINKEDLIST_H

LinkedList.cpp
//
// Created by ngkimbing on 10/4/19.
//
#ifdef ACM_LINKEDLIST_H

#include "LinkedList.h"

template<typename T>
void LinkedList<T>::push_back(T ele) {
    Node<T> *temp = new Node<T>(ele);
    tail->next = temp;
    tail = temp;
    ++size;
}

template<typename T>
typename LinkedList<T>::Iterator LinkedList<T>::begin() {
    return Iterator(head);
}

template<typename T>
typename LinkedList<T>::Iterator LinkedList<T>::end() {
    return Iterator(tail);
}

template<typename T>
LinkedList<T>::LinkedList() {
    head = new Node<T>;
    tail = head;
}
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值