首页 > 解决方案 > 如何访问 std::queue 数据结构的成员元素?

问题描述

使用 Visual Studio 2019 在 C+ 中编码,我定义了一个结构。我正在创建该数据结构的队列,并将 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;
}

标签: c++queuevisual-studio-2019std

解决方案


好吧,front返回对第一个元素的引用,就像这样:

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

或者,例如,自己做一个参考:

auto& ref = myQ.front();

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

推荐阅读