向量和队列C++

Vectors and queues C++

本文关键字:C++ 队列 向量      更新时间:2023-10-16

这是前面关于如何压缩开关语句的问题的后续。我使用了之前提供的输入,但是我收到有关如何将元素插入向量的错误,但我认为这就是您在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...?
}