简体   繁体   English

如何在我的课程中定义迭代器

[英]How to define a iterator in my class

I use iterator in C++.It is so good.But I want have a my iterator in my class.how to do? 我在C ++中使用迭代器,效果很好,但是我想在我的类中使用我的迭代器,怎么办?

a simple example 一个简单的例子

//a simple container
class MyArray
{
public:
    MyArray()
    {
        for(int i=0;i<10;i++)
            data[i] = 0;
    }

    int GetValue(int index)
    {   
        if(index>=10 || index<0)
            return -1;
        else
            return data[index]; 
    }

    bool SetValue(int value, int index)
    {
        if(index>=10 || index<0)
            return false;
        data[index] = value;
    }

    int& operator[](int index)
    {   return data[index]; }

    void ShowData();
protected:
    int data[10];
private:
};

// only test use
void MyArray::ShowData()
{
    std::cout<<"Data : ";
    for(int i =0;i<10;i++)
    {
        std::cout<<data[i]<<" ";
    }
    std::cout<<std::endl;
}

int main()
{
    MyArray array;

    MyArray::iterator it = array.begin();   //how to implementation?

    getchar();
    return 0;
}

The C++11 standard defines the requirements for iterators in section 24 of the standard. C ++ 11标准在该标准的第24节中定义了对迭代器的要求。 So, the short answer here is for you to define and implement your iterator and const_iterator class in a manner that meets the requirements for iterators. 因此,这里的简短答案是让您以满足迭代器要求的方式定义和实现iteratorconst_iterator类。

The requirements for iterators take up five terse pages in the standard. 迭代器的要求在标准中占据了五个简短的页面。 Obviously, that's not something that can be summarized in a few short paragraphs in a stackoverflow.com answer. 显然,这不是可以在stackoverflow.com答案中的几个简短段落中总结的内容。

I would suggest that you visit a library or a book store, look for a thorough book on C++, browse it, and see if it provides a good, substantive review of iterators and their requirements. 我建议您访问图书馆或书店,查找有关C ++的详尽书籍,进行浏览,看看它是否对迭代器及其要求提供了很好的实质性审查。 Then try to implement them yourself. 然后尝试自己实现它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM