开发者

Custom iterator: how do I keep track of it?

开发者 https://www.devze.com 2023-01-04 15:55 出处:网络
I have this situation: I have a class which keeps track of an array of pointers. I built a custom iterator which loops through this array.

I have this situation:

I have a class which keeps track of an array of pointers. I built a custom iterator which loops through this array.

My problem is on how to make it threadsafe, especially while incrementing/decrementing?

Here is a draft of the relevant parts of what I have:

typedef fruit * iterator;

class fruits
{
  private:
    fruit ** flist;
    int n;     //keeps track of position in flist
    int count; /开发者_如何学Go/number of fruits

  public:
    iterator begin() {n=0; return fruit[n];}
    iterator end() {n=count; return fruit[n];}

    iterator operator++ ()
    {
      return fruit[++n];
    }
}

The problem i see is that if two parts of the program create an iterator things won't work. How does C++ STL deal with it?

UPDATE: I have found the error of my ways. The iterator should keep track of where it is by itself. For that I created an iterator class embedded in my main class. Life is now good.


The standard containers maintain their iteration state in iterator objects separately from the container, so there can be multiple iterations over the container at the same time. So begin() and end() return iterators, but don't change the state of the container; operator++ acts on iterators, not the container. For a simple array like this, a pointer (to a fruit*, not a fruit) works perfectly well as an iterator, so you can just define begin() and end():

iterator begin() {return flist;}
iterator end() {return flist + count;}

and use it like this:

for (iterator i = my_fruit.begin(); i != my_fruit.end(); ++i)
    do_something_with(*i); // *i is a fruit*

There's no problem with multiple threads doing this at the same time, as long as none of them try to modify the container.

On the other hand, unless this is a learning exercise to better understand how containers and iterators work, you're much better off using std::vector than implementing your own version of it.

0

精彩评论

暂无评论...
验证码 换一张
取 消