我正在讨论,如果我使用数据结构在类中存储回调,在启动时应该使用向量和保留,还是在这种情况下只使用deque,因为订阅用户的总数未知,但相对较小,大约为15。我想,在这两种情况下,每次分配与在我的课堂上提前准备命中之间的权衡是什么。
#ifndef __Pricer_hpp__
#define __Pricer_hpp__
#include <utility>
#include <vector>
class Pricer
{
public:
typedef void (*callback_fn)(double price, void *subscription);
Pricer(): _initialSubscriberNum(15), _callbacks() { _callbacks.reserve(_initialSubscriberNum); } // is it better to use a deuqe and remove the need for the reserve?
void attach (const callback_fn& fn, void *subscription )
{
_callbacks.emplace_back(fn,subscription); // is emplace_back better than using push_back with std::pair construction which I am assuming would do a move version of push_back?
}
void broadcast(double price)
{
for ( auto callback : _callbacks)
{
(*callback.first)(price, callback.second);
}
}
private:
typedef std::pair<callback_fn, void *> _callback_t;
const unsigned int _initialSubscriberNum;
std::vector<_callback_t> _callbacks; // should this be a deque?
};
#endif
一般建议是使用向量,然后如果您有一些性能问题(在您的情况下可能不会发生),则更改为其他数据结构。
记住"过早优化"有时会造成伤害。
push_back与template_back此处链接