Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在我的类中定义迭代器 我在C++中使用迭代器。它很好。但是我想在我的类中有一个迭代器。怎么办?< /P>_C++_Iterator - Fatal编程技术网

如何在我的类中定义迭代器 我在C++中使用迭代器。它很好。但是我想在我的类中有一个迭代器。怎么办?< /P>

如何在我的类中定义迭代器 我在C++中使用迭代器。它很好。但是我想在我的类中有一个迭代器。怎么办?< /P>,c++,iterator,C++,Iterator,一个简单的例子 //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

一个简单的例子

//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;
}
//一个简单的容器
类MyArray
{
公众:
MyArray()
{

对于(int i=0;i=10 | | index=10 | | index,C++11标准在标准的第24节中定义了对迭代器的要求。因此,这里的简短回答是让您以满足迭代器要求的方式定义和实现
迭代器
常量迭代器

迭代器的要求在标准中占据了5页的篇幅。显然,这不是一个
stackoverflow.com
答案中的几个简短段落所能概括的


<>我建议你去图书馆或书店,寻找一本关于C++的详尽书籍,浏览它,看看它是否提供了对迭代器及其需求的一个好的、实质性的评论。然后尝试自己实现它们。

可能的副本,如果你想要便宜的方式,指针就可以算作随机存取迭代器。nal标准库函数,仅适用于迭代器对象,可以使用指针代替。