无法在 C++ 中实现队列 <pair<int, int*> >

Cannot implement queue <pair<int, int*> > in C++

问题:

我正在尝试实现具有结构 queue <pair<int, int*> > 的缓冲区。在下面的代码中,我试图将 100 条记录推送到缓冲区队列中。在那之后,我试图再次从缓冲区中一条一条地拉取记录:

#include <bits/stdc++.h>

using namespace std;

int main() {
    typedef int TWO_INT_ARR[2];
    typedef pair<int,int*> data_record;

    queue<data_record>* _buffer = new queue<data_record>();

    for(int i=0; i<100; ++i) {
        TWO_INT_ARR _two_int_arr;

        _two_int_arr[0] = i;
        _two_int_arr[1] = i;

        data_record     _data_record;

        _data_record.first = i;
        _data_record.second = _two_int_arr;

        _buffer->push(_data_record);
    }

    while(! _buffer->empty()) {
        data_record front_record = _buffer->front();

        cout << front_record.first << "\t"
                << front_record.second[0] << "\t"
                << front_record.second[1] << endl;

        _buffer->pop();
    }

    return 0;
}

预期输出:

0    0    0
1    1    1
2    2    2
:    :    :
99   99   99

实际输出:

0    99   99
1    99   99
2    99   99
:    :    :
99   99   99

谁能帮我找出代码中的错误?

你有一个很大的内存管理问题。

首先,不要为您的数据使用 C 风格的数组,请使用 std::array。然后,不要使用 bits/stdc++.h:

typedef std::array<int, 2> TWO_INT_ARR;
typedef std::pair<int, TWO_INT_ARR > data_record;

std::queue<data_record>* _buffer = new std::queue<data_record>();

就是这样。

也同意@Fureeish。如果这是一个最小的例子,那么你可以使用:

std::queue<data_record> _buffer;

对于这个例子。