面向对象的迭代std :: vector的方法?

jma*_*erx 5 c++ oop vector

我有一个类有一个子控件指针的std :: vector.出于显而易见的原因,我不希望类的用户直接访问std :: vector.我想要的只是给调用者提供指针的方法.什么是一个很好的OO方式来做到这一点?(此功能将经常调用)

谢谢

Jos*_*shD 14

提供一个返回const_iterator向量的函数.添加一个以将迭代器返回到向量的末尾也很有用.

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's useful and not too invasive.
  const T& getAt(int i) const {return v.at(i);}

  //stuff
  vector<T> v;
};
Run Code Online (Sandbox Code Playgroud)

  • 通常最好为用户提供typedef,因此他们不太可能将`vector <T> :: const_iterator`硬编码为他们将检索到的迭代器放入的变量类型,这需要编辑客户端代码应该MyClass更改其数据表示. (5认同)