将指针数组推入 std::vector 避免使用 push_back 复制对象

Pushing an array of pointers into a std::vector avoiding copying the objects with push_back

在此代码中,在 for 循环中创建了一个指针数组 newData,然后将其推入向量 testData。指针存储在向量 std::vector<testData*>.

我担心的是我需要确保指针引用的对象在向量持有对它们的引用时仍然有效。我是否会通过在 for 循环中调用行 newData = new unsigned char[frameSize]; 来丢失此引用?

我主要是想避免复制带有push_back的对象。

如何创建一个 unsigned char* 的随机字符数组(这里我只使用 'a'),然后将这些数组推送到向量中?

int numFrames = 25;
int frameSize = 100;

std::vector<unsigned char*> testData;

unsigned char *newData;

for (int i = 0; i < numFrames; i++) {
    newData = new unsigned char[frameSize];

    for (int j = 0; j < frameSize; j++) {
        newData[j] = 'a'; // fill the frame with random data, 'a' here
    }

    testData.push_back(newData);
    newData = 0; // ??
    memset(&newData, 0, frameSize); // ??
}

std::cout << " testData " << testData.size() << "\n";

Do I lose this reference by calling the line newData = new unsigned char[frameSize]; in a for loop?

不,如果操作正确,完全可行。

虽然你的代码有一些问题,在行 memset(&newData, 0, frameSize); // ?? 中你设置了一个指针占用的内存,它通常不超过 8 个字节(取决于架构)和一个大小100 字节,这会调用未定义的行为。你可能想要:

memset(&newData, 0, sizeof newData); // ??

但这不会满足您的需求,使指针无效会使您无法访问数据,您不希望这样,并且您在每次迭代中都将相同的指针推向向量,您最终会得到一个向量,其中包含指向相同数据的相同指针。

将它的声明移到 for 循环中可以解决这个问题。您没有复制任何数据,而是在每次新迭代时将指向新内存位置的新指针推送到向量中。

How can I create an array of unsigned char* of random char (here I just use 'a') and then push these arrays to the vector?`

您的代码应如下所示:

Live demo

#include <iostream>
#include <vector>
#include <ctime>
int main()
{   
    srand(time(0)); //seed, not the best randomizer but does the job here
    
    const size_t numFrames = 25; //sizes can/should be constant and unsigned
    const size_t frameSize = 100;

    std::vector<unsigned char *> testData;

    for (size_t i = 0; i < numFrames; i++)
    {
        //in each iteration a new pointer
        unsigned char *newData = new unsigned char[frameSize];

        for (size_t j = 0; j < frameSize; j++)
        {
            newData[j] = 'a' + rand() % 26; //random alphabetic char
        }
        testData.push_back(newData);
    }
    
    std::cout << "testData " << testData.size() << "\n";        
    
    for (size_t i = 0; i < numFrames; i++) //test print
    {
        for (size_t j = 0; j < frameSize; j++)
        {
            std::cout << testData[i][j];
        }
        std::cout << "\n";
    }
}

不用说,您应该 delete 您以前分配的内存,当您不再需要它时。

如果你想要一个更好的随机引擎,你可以检查这个 post Generate random numbers using C++11 random library.

一些注意事项:

您可能知道 newData 指针指向的数据不能被视为字符串,也就是空终止字符数组,因为当然,它们不是空终止的。

您需要手动管理您分配的内存,也就是说手动保留的内存在您使用完后也必须手动删除。

代码更正是针对您的代码的,但作为 ,您可能最好在周围使用 STL 容器而不是指针。