gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:46 24 4
gpt4 key购买 nike

我有一个类,它有一个 std::vector 子控件指针。出于显而易见的原因,我不希望类的用户直接访问 std::vector。我想要的只是一种为调用者提供指针的方法。什么是好的 OO 方法来做到这一点? (这个函数会经常被调用)

谢谢

最佳答案

提供一个函数,返回一个 const_iterator 给 vector 。加一返回迭代器到 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's useful and not too invasive.
const T& getAt(int i) const {return v.at(i);}

//stuff
vector<T> v;
};

关于c++ - 迭代 std::vector 的面向对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3911098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com