使用元素加载 std::queue<uint8_t*> 的更有效方法?

More effective way to load a std::queue<uint8_t*> with elements?

本文关键字:gt 有效 方法 queue 元素 std lt uint8 加载      更新时间:2023-10-16

我正在尝试找到一种更有效的方法,将uint8_t字节的变量阵列加载到std :: queue

以下代码段是试图将实际代码简化为更可用的例子的尝试;所以请原谅我是否过于复杂。

代码片段有效,除了我无法确定std ::队列的每个元素的实际长度,而它们仍在队列的前面。我的问题是,"是否有任何方法可以将指针推向未签名的字节数组,而没有创建本地数组的中间步骤,将传递的参数复制到其中然后推动本地指针(请参阅代码中的注释(?

#include <queue>
#include <string>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
using namespace std;
std::queue<uint8_t*> _q;
void routineSubroutine(uint8_t array_a[], int size_a)
{
    /*
     * Is there anyway to push the uint8 array_a into the queue (_q) without
     * creating a new pointer to a byte array, copying the passed
     * argument into it and the pushing it?
     */
    uint8_t* a = new uint8_t[size_a];
    memcpy((void*) a, (const void*) array_a, size_a);
    _q.push(a);
}
int main(int argc, char** argv)
{
    uint8_t myArray[512];
    char cfa[] = {"I wish I was at Chick-Fil-A right now"};
    memset((void*) myArray, 0x00, sizeof (myArray));
    memcpy((void*) myArray, (const void*) cfa, strlen(cfa));
    routineSubroutine(myArray, strlen(cfa));
    char five[] = {"Five Guys will do in a pinch"};
    memcpy((void*) myArray, (const void*) five, strlen(five));
    routineSubroutine(myArray, strlen(five));
    while (_q.size() > 0)
    {
        printf("Queue string value = %sn", (char*) _q.front());
        /*
         * How do I go about determining the number of bytes in the uint8_t
         * array, whose address is at the front of the queue?
         */
        _q.pop();
    }
    return 0;
}

代码片段有效,除了我无法 确定std ::队列每个元素的实际长度 当他们仍在队列的前面

使用知道其长度/大小的适当容器,并调用适当的成员功能。单纯的指针不这样做。

这是您重写std::vector的代码的示例:

#include <queue>
#include <string>
#include <vector>
#include <iostream>
std::queue<std::vector<uint8_t>> _q;
void routineSubroutine(const std::vector<uint8_t>& a)
{
    _q.push(a);
}
int main(int argc, char** argv)
{
    char cfa[] = {"I wish I was at Chick-Fil-A right now"};
    routineSubroutine({std::begin(cfa), std::end(cfa)}); // creates a temp uint8_t vector
    char five[] = {"Five Guys will do in a pinch"};
    routineSubroutine({std::begin(five), std::end(five)}); // creates a temp uint8_t vector
    while ( !_q.empty() )
    {
        // use the `write()` function to control the number of characters
        std::cout.write(reinterpret_cast<const char *>(_q.front().data()), _q.front().size());
        std::cout << "n";
        _q.pop();
    }
    return 0;
}

输出:

I wish I was at Chick-Fil-A right now
Five Guys will do in a pinch

最终,我可以完全控制自己可以使用的队列的类型,而我对数据的显示方式有零控制。具体而言,数据以UINT8_T*和size_t长度表示。多亏了 @paulmckenie的示例代码,我能够提出以下解决方案(顺便说一句,这是邪恶的快速(:

std::queue<std::vector<uint8_t>> myQueue;
while(true)
{
    // Pointer (myBuffer) and length (myLength) magically appear here
    myQueue.push({myBuffer, (uint8_t*) (myBuffer + myLength)});
}

解决问题。