用于值检查的自定义迭代器

Custom iterator for value checking

我是迭代器的新手,正在尝试获得更多关于它们的知识。

这就是为什么我试图创建一个自定义迭代器来遍历给定的字符串数组,以检查该字符串的任何值是否为十进制值。我想出了下面给出的实现:

Collection 是我迭代器的用户

// Collection type
template <class T, int N>
class Collection
{
    // Holder for our collection
    // N is the size for our collection
    T data[N];

public:

    Collection(T _data[N]) { copy_n(_data, N, data); }

    // Method to return the iterator to the beginning of the collection
    CollectionIterator<T> begin()
    {
        return CollectionIterator<T>(data);
    }
    // Method to return the iterator to the end of the collection
    CollectionIterator<T> end()
    {
        return CollectionIterator<T>(data + N);
    }
};

CollectionIterator 是我的自定义迭代器(具有输入迭代器的类型)

template <class T>
class CollectionIterator
{
    T *data;

public:
    using iterator_category = std::input_iterator_tag;
    using value_type = T;
    using difference_type = size_t;                         
    using pointer = T*;
    using reference = T&;

    // Default constructor
    CollectionIterator(){}
    CollectionIterator(pointer _data): data(_data) {}

    reference operator*()
    {
        if(is_number(*data))
        {
            std::cout << *data;
        }
        return *data;
    }

    bool operator!=(const CollectionIterator &other)
    {
        return data != other.data;
    }

    CollectionIterator<T>& operator++()
    {
        data += 1;
        return *this;
    }

    CollectionIterator<T> operator++(int)
    {
        return CollectionIterator<T>(data + 1);
    }

    bool is_number(const std::string& s)
    {
        return !s.empty() && std::find_if(s.begin(),
            s.end(), [](unsigned char c) { return !std::isdigit(c); }) == s.end();
    }
};

下面你可以看到我如何使用集合 class。

std::string s[8] = { "2", "hello", "world", "asd5", "19870717", "sadsad7", "8", "byby" };

Collection <std::string, 8> test (s);

for (auto t = test.begin(); t != test.end(); t++){ }

当我 运行 代码时,我想看到 2 19870717 8 但它不打印任何内容。我是不是遗漏了什么或者我的代码有什么问题?

所以基本上,我的 post 和预增量实现是不正确的。当我如下更改它们时,它起作用了。

bool operator==(const CollectionIterator &other)
{
    return data == other.data;
}

CollectionIterator<T>& operator++()
{
    data++;

    return *this;
}

CollectionIterator<T> operator++(int)
{
    CollectionIterator i = *this;

    data++;

    return i;
}