1

我有一个内存,我用char * p它来访问它。

我想要一个参考。我该怎么做?

vector<char>& v = p

我需要做什么而不是 p 将其转换为向量,我还需要告诉它我在内存中使用的 char * 的大小。

4

3 回答 3

1

本质上:

  • 向量拥有它的内存,它不只是引用它。所以你可以创建一个新的向量来复制你的数据,但你不能让向量“获取”你的指针并使用它。

  • 如果您必须有一个向量才能传递给第 3 方 API 并且您有一个指针,则您必须制作一个副本

  • 如果您可以控制 API,则可以将其更改为采用一系列指针(开始/结束)或指针和大小。这样,如果您已经有一个向量,您仍然可以访问这些函数(尽管您不能期望begin()end()给您指针。但是有一些方法可以将这些作为指针使用&v[0],然后将大小添加到该指针)。

  • 如果您只需要将数据放入标准算法中,您已经可以使用指针来完成。

显然,如果你有一个指针,你不能执行修改数据大小的向量操作,例如 push_back。但是由于您char*没有 a const char*,您可以修改成员。

于 2012-12-31T14:30:07.100 回答
1

It's hard to answer this question without more information but I'll try. The most straight forward solution is probably to cast p to the correct type of pointer, and then construct a new vector. If you want a vector of chars:

std::vector<char> wewvec(p,p+20) 

where 20 is where you'll give the number of element. That is, if the data is really char.

If the data is of some other type, say it contains 20 floats, you could do:

const float* pf=reinterpret_cast<const float*>(p);
std::vector<float> wewvec(pf,pf+20) 

As Dietrich writes, this will copy the data into the new vector.

于 2012-12-31T09:35:18.580 回答
0

如果你有一个指向内存块的指针 p

char* p = new char[100];

您可以通过编写来创建对它的引用

char& q = *p;

如果您使用容器vector,则需要将内容复制到向量中,如 Johan 所说

于 2012-12-31T10:05:41.300 回答