如何访问 std::queue 数据结构的成员元素?

How to access member elements of a std::queue data structure?

在 C+ 中编码,使用 Visual Studio 2019,我定义了一个结构。我正在创建该数据结构的队列,并将 2 个元素推入队列。现在的问题是如何访问队列内部结构元素的成员?任何指导表示赞赏!

#include <iostream>

#include <sstream>
#include <cstdlib>

#include <queue>

typedef struct _myqueuestruct
{
    string name;
    int citypin;
    int employeeId;
}myqueuestruct;


int main()
{
    queue<myqueuestruct> myQ;
    myqueuestruct myQelement;
    
    myQelement.name = "Harry";
    myQelement.citypin = "Ohio";
    myQelement.employeeId = "345";

    // Insert some elements into the queue
    myQ.push(myQelement);

    myQelement.name = "John";
    myQelement.citypin = "Jaipur";
    myQelement.employeeId = "223";

    // Insert some elements into the queue
    myQ.push(evtSvcElement);
    //myQ.size();

    //queue<myqueuestruct>::iterator it = myQ.begin();

    for (int i = 0; i < myQ.size(); i++)
    {
        cout << myQ.front();
        myQ.pop(); //???? How do I access the member values of the elements of the queue?
    }

    while (1);
    return 0;
}

嗯,front returns 对第一个元素的引用,所以像这样:

std::cout << myQ.front().name; // and similarly for other elements

或者,比如自己做个参考:

auto& ref = myQ.front();

ref.name = "foo";
ref.citypin = 42;
// etc.

我修改了您的代码以使其编译和工作:(注意:我使用 C++17 标准使用 g++ 来编译此代码,但它应该适用于 visual studio 2019

#include <iostream>
#include <queue>

typedef struct _myqueuestruct
{
    std::string name;
    std::string citypin;
    int employeeId;
}myqueuestruct;


int main()
{
    std::queue<myqueuestruct> myQ;
    myqueuestruct myQelement;
    
    myQelement.name = "Harry";
    myQelement.citypin = "Ohio";
    myQelement.employeeId = 345;

    // Insert some elements into the queue
    myQ.push(myQelement);

    myQelement.name = "John";
    myQelement.citypin = "Jaipur";
    myQelement.employeeId = 223;

    // Insert some elements into the queue
    myQ.push(myQelement);

    while (myQ.size() > 0)
    {
        auto & e = myQ.front();
        std::cout << "Name: " << e.name
            << " CityPin: " << e.citypin
            << " EmployeeId: " << e.employeeId << std::endl;
        myQ.pop();
    }

    return 0;
}

我想指出我必须在上面的代码中进行的一些更改:

  • 在您的结构定义中,您使用了 int 数据类型,但您将 char string 分配给了相同的数据类型。我已将数据类型修改为 std::string.
  • 使用 while 循环遍历所有元素并每次使用 myQ.size() 而不是使用 for 循环。
  • std::cout - 将元素引用保存在循环内的局部变量中并打印所有成员变量。

您可以对以上代码进行的改进:

  • 当您将对象推入队列时,创建了对象的多个临时副本。我建议在此处参考 std::queue 文档:http://www.cplusplus.com/reference/queue/queue/ 并尝试使用 emplace_back
  • 为您的 class 重载 operator<< 以打印 class 成员,这将帮助您了解运算符重载。