向量和队列C++
Vectors and queues C++
这是前面关于如何压缩开关语句的问题的后续。我使用了之前提供的输入,但是我收到有关如何将元素插入向量的错误,但我认为这就是您在C++中插入向量的方式?
std::queue<myStruct > myQueue1, myQueue2, myQueue3, myQueue4, myQueue5
void change(float posx, float posy, int idNumber){
myStruct newDir;
newDir.psX = posx;
newDir.psY = posy;
std::vector< std::queue<myStruct> > myVector (5);
myVector.begin();
myVector.insert (myQueue1);
myVector.insert (myQueue2);
myVector.insert (myQueue3);
myVector.insert (myQueue4);
myVector.insert (myQueue5);
if (idNumber >= 1 && idNumber<= 5){
myVector[idNumber-1].push (newDir);
}
}
TIA任何帮助表示赞赏。
vector::insert()
用于在特定位置插入新元素(因此它需要一个位置参数)。 您可能只想要将新项放在向量末尾push_back()
。为此,您不希望像现在这样初始化向量(这会在向量上放置五个空队列);只是默认初始化向量:
std::vector< std::queue<locaRef> > myVector;
但是还有一个问题是,你的向量有类型std::queue<locaRef>
的元素,但你在向量上放置的队列是std::queue<MyStruct>
的。 即使你修复了类型差异,你也需要记住,将被放入向量的是队列的副本,这可能是你想要的,也可能不是你想要的。 如果您不需要副本,您可能希望向量采用某种指向队列对象的指针或智能指针。
如果您无论如何都要对队列数进行硬编码 5,您可以简单地使用数组而不是vector
。 通常,为了方便起见,您会为您的结构提供一个简单的构造函数:
struct My_Struct
{
My_Struct(float posx, float posy) : posx_(posx), posy_(posy) { }
float posx_, posy_;
};
std::queue<My_Struct> my_queues[5];
void change(float posx, float posy, int id_number)
{
if (id_number >= 1 && id_number <= 5)
my_queues[id_number - 1].push(My_Struct(posx, posy));
// else throw or assert so you'll see there's a problem...?
}
相关文章:
- boost::进程间消息队列引发错误
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Android NDK传感器向事件队列报告奇怪的间隔
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 按对象的特定方法按升序排列的C++优先级队列
- 使用2个键的cpp-stl::优先级队列排序不正确
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 在一个读写器队列中,我可以用volatile替换原子吗
- 为什么我的多线程作业队列崩溃
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 使用"Task"函数指针队列定义作业管理器
- 在c++队列中使用pop和visit实现线程安全
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 打印优先级队列
- 共享队列的线程安全
- 带自定义比较器的最小优先级队列
- 在 Vulkan Qt 中获取队列系列
- 堆栈和队列是否像C++中的数组一样传递?
- 在C++中创建队列 - 什么是 malloc 错误?
- 优先级队列自定义比较器