学弟的一个问题让我发现了自己的一个知识盲区
问题:
统计字符串中的字母,数字,符号的个数,并删除数字
联想:
问题本身是很简单的,但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