Object oriented way of iterating through std :: vector?

I have a class that has a std :: vector pointer to a child control. For obvious reasons, I do not want the class user to have direct access to std :: vector. All I would like is a way to give pointers pointers. What would be a good OO way to do this? (this function will be called often)

thank

+5
source share
3 answers

Provide a function that returns const_iteratorto the vector. It is also useful to add one to return the iterator to the end of the vector.

class MyClass {
public:
  typedef vector<T>::const_iterator c_iter;

  c_iter getBegin() const {return v.begin();}
  c_iter getEnd() const {return v.end();}

  // and perhaps if it useful and not too invasive.
  const T& getAt(int i) const {return v.at(i);}

  //stuff
  vector<T> v;
};
+14
source

- , . - : , , :

  • , ,
  • , , .
  • , -

  • , : . , , , , : - / , - ( , ). ( ). , , begin(), , , find(): .

:

class Container
{
  public:
    template <typename Visitor>
    void visit(Visitor& visitor)
    {
        for (Vector::const_iterator i = v_.begin(); i != v_.end(); ++i)
             visitor(*i);
    }

  private:
    typedef std::vector<X> Vector;
    Vector v_;
};

// client code...

struct Visitor
{
    void operator()(const X&) { ... }
    // any data you want to update as you iterate...
};

Visitor v(...any construction arguments...);
container.visit(v);
+3

:

class MyClass {
public:   
  const unsigned int GetNumberOfItems() { return v.size(); }

  T* GetItemNumber(const unsigned int n) 
  {
    // 3 options here, thrown your own exception type, or use the std one, or
    // or just return NULL meaning nothing there or out of range.
    try{
      return v.at(n);
    } catch (std::out_of_range &e){
    }

    return NULL;    
  }

  vector<T> v;
};

- :

MyClass cl;
int count = cl.GetNumberOfItems();
for (int i = 0; i < cl.GetNumberOfItems(); i++){
  T* item = cl.GetItemNumber(i);
}

No iterators in the outside world are required. If you've ever had to expose something like the standard C API, then it's very easy to expose.

+1
source

All Articles