在这段代码中,指针数组 newData
在 for 循环中创建,然后将其插入 vector testData
.指针存储在 vector std::vector<testData*>
中.
我担心的是我需要确保指针引用的对象在 vector 持有对它们的引用时仍然有效。我是否会通过调用 newData = new unsigned char[frameSize];
行丢失此引用?在for循环中?
我主要是想避免使用 push_back
复制对象.
如何创建 unsigned char*
的数组随机字符(这里我只使用 'a'
),然后将这些数组推送到 vector ?
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); // ??
但这不会满足您的需要,使指针无效会使您无法访问数据,您不希望这样,并且您在每次迭代中都将相同的指针推向 vector ,您最终会得到一个 vector 填充了指向相同数据的相同指针。将其声明移入
for
循环将解决这个问题。您没有复制任何数据,而是在每次新迭代时将指向新内存位置的新指针插入 vector 中。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
当您不再需要它时,您之前分配的内存。如果你想要一个更好的随机引擎,你可以查看这篇文章 Generate random numbers using C++11 random library .
一些笔记:
正如您可能知道
newData
所指向的数据指针不能被视为一个字符串,也就是一个以 null 结尾的 char 数组,因为当然,它们不是以 null 结尾的。您需要手动管理分配的内存,也就是说,手动保留的内存也必须在完成后手动删除。
代码更正适用于您的代码,但为 WhozCraig correctly points out ,你可能会更好地使用 STL 容器而不是指针。
关于c++ - 将指针数组插入 std::vector 避免使用 push_back 复制对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64536266/