可变大小和类型的队列的类结构
Class structure for a queue of variable size and type
我更像是一个硬件人员,但我使用的芯片设计工具需要我编写一些C++代码。我不熟悉面向对象编程;虽然我对 C 有很好的处理。我所要求的是解释如何构建我的类(称为cq
)来完成手头的任务。
我希望能够生成指定数据类型和指定大小的队列(生成后不应更改)。理想情况下,这将像这样完成...
my_queue = new cq(uint8_t, 6);
。这将生成一个由六个 8 位无符号整数组成的数组(或向量)。
然后,我想要一种方法来将元素插入末尾并返回队列头部的元素,如下所示。
uint8_t front;
front = my_queue.advance(28);
我需要什么样的结构来完成此操作?由于数据类型是可变的,我是否需要模板?或者我应该有一个泛型类,并让每个数据类型的类继承其结构?
谢谢!
编辑:使用下面答案的输入,我想出了以下内容:
template <class type>
template <class size>
class CQ {
private:
// Allocates a queue with type and size
// specified by template arguments.
std::queue<type> cycle_queue(size, 0);
public:
// Inserts input to the end of the queue;
// removes and returns the front element.
type advance(type in){
type out = cycle_queue.front();
cycle_queue.push_back(in);
cycle_queue.pop_front();
return out;
}
}
然后我的问题变成了...如何在我的主C++程序中实例化它?我试过这个,但它不起作用:
CQ<uint8_t><6> my_queue;
my_queue.advance(28);
再次感谢!
考虑使用 stl containers
,例如 std::vector
(此处:http://www.cplusplus.com/reference/vector/vector/)或std::list
(此处:http://www.cplusplus.com/reference/list/list/)。这些集合已经完成了您想要实现的目标,您的类只需实现该集合的访问器。
原型如下所示:
std::vector Variable<uint8_t>;
或者,您需要使用 Templates
.有关它们是什么以及它们如何工作的全面解释可以在这里找到:http://www.cplusplus.com/doc/tutorial/templates/
本质上,您将声明您的对象
cq<uint8_t>(6);
在构造函数中,您将输入:
template <class T>
cq::cq(int amount) {
Buffer = new T[amount];
}
使用"free"完成后,请不要忘记解除分配内存。
这看起来像是STL容器的完美应用程序。 您可以编写自己的队列类(作为模板类,因为您希望能够指定数据类型),但为什么要重新发明轮子呢?
您可能正在寻找: std::list
,用于 FIFO 队列。 对于您的特定示例:
std::list<uint8_t> my_queue;
my_queue.push_back(28); // push an element
uint8_t front = my_queue.front(); // get the element on the front of the queue
my_queue.pop_front(); // and then pop it
如果您还不太熟悉 OOP 和 C++,那么编写自己的模板类现在可能有点遥不可及。 网上到处都有很好的参考资料,但如果你想尝试的话:例如 http://www.cplusplus.com/doc/tutorial/templates/
尝试:
#include <cstdio>
#include <queue>
int main(int argc, char * argv[])
{
std::deque<int> myQueue;
myQueue.push_back(1);
myQueue.push_back(2);
myQueue.push_back(3);
for (int i = 0; i < 3; i++)
{
int j = myQueue.front();
printf("%d ", j);
myQueue.pop_front();
}
getchar();
}
<小时 />编辑:回应评论
我想到的最简单的解决方案是:
myQueue.push_back(newValue);
while (myQueue.size > 6)
myQueue.pop_front();
实际上,您可以轻松地将此代码包装在自己的类中,如下所示:
template <class T>
class SixItemsQueue
{
private:
std::deque<T> data;
public:
void Push(T value)
{
data.push_back(value);
while (data.size() > 6)
data.pop_front();
}
T Pop()
{
T result = data.front();
data.pop_front();
return result;
}
};
- C++ 中优先级队列的结构排序条件
- 优先级经常更改的作业优先级队列的数据结构
- C++ 数据结构队列:使用 for 循环查找队列中最大的元素
- 从 STL 优先级队列C++ (QtCreator) 打印结构
- C 在标题文件中创建具有结构定义的结构的队列
- 在 stl 中迭代结构类型的队列
- 从指针队列访问结构的成员
- 使用提升库在队列和堆栈数据结构上保存和加载数据时出错
- 优先队列中的结构比较
- C 单例结构队列
- 我的字符串队列结构有什么问题?
- 结构类似优先级队列,但具有类似下界的内容
- 使用队列<结构时出现 SIGSEGV 错误 *>
- 工作线程队列的这种变体是某种模式或通用结构吗?
- 排序结构的队列
- 在队列中推动结构变量
- 从头开始实现队列结构 (C++)
- 队列结构会产生奇怪的错误
- c++中队列结构中的Struct节点
- 使用队列结构c++的离散事件模拟