template <typename Compare>class CustomOrderList {public: void append(order::Order* pOrder) { m_orderList.insert(pOrder); } void remove(order::Order* pOrder) { m_orderList.erase(pOrder); } size_t size() const { return m_orderList.size(); } bool empty() const { return m_orderList.empty(); } template <typename Func> void apply(const Func& func) const { func(m_orderList); }private: std::set<order::Order*, Compare> m_orderList;}; 实现迭代器功能,const版本
时间: 2024-01-26 08:05:14 浏览: 82
可以通过定义一个内部类 Iterator 来实现迭代器功能,其中 const 版本需要返回 const 指针。
具体实现如下:
```c++
template <typename Compare>
class CustomOrderList {
public:
// 内部迭代器类定义
class Iterator {
public:
Iterator(typename std::set<order::Order*, Compare>::const_iterator it) : m_it(it) {}
bool operator==(const Iterator& other) const { return m_it == other.m_it; }
bool operator!=(const Iterator& other) const { return m_it != other.m_it; }
order::Order* operator*() const { return *m_it; }
Iterator& operator++() { ++m_it; return *this; }
private:
typename std::set<order::Order*, Compare>::const_iterator m_it;
};
void append(order::Order* pOrder) {
m_orderList.insert(pOrder);
}
void remove(order::Order* pOrder) {
m_orderList.erase(pOrder);
}
size_t size() const {
return m_orderList.size();
}
bool empty() const {
return m_orderList.empty();
}
// const 版本迭代器
Iterator begin() const {
return Iterator(m_orderList.cbegin());
}
Iterator end() const {
return Iterator(m_orderList.cend());
}
template <typename Func>
void apply(const Func& func) const {
func(m_orderList);
}
private:
std::set<order::Order*, Compare> m_orderList;
};
```
使用示例:
```c++
CustomOrderList<MyCompare> orderList;
// 添加订单
orderList.append(new order::MarketOrder);
orderList.append(new order::LimitOrder);
orderList.append(new order::StopOrder);
// 遍历订单
for (auto it = orderList.begin(); it != orderList.end(); ++it) {
std::cout << (*it)->getType() << std::endl;
}
```
阅读全文