[英]array of pointers to vector of pointers
正如有人指出的那樣,使用數組向量看起來通常比使用指針數組更合理; 所以在這里我有一個指針數組,我想將其轉換為數組向量:
char ** ptr;
char * ptrContiguous;
ptr = new char*[numChannels];
ptrContiguous = new char[x*y*byteSize*nC*nM*nZ*nT];
char * p = ptrContiguous;
for(int i = 0; i < numChannels; i++)
{
ptr[i] = p;
p += x*y*byteSize;
}
我的問題是:只有ptr需要轉換為向量嗎? 有人可以編寫一些簡單的代碼來說明數組到矢量轉換嗎? 謝謝。
這是你的實際代碼:
char ** ptr;
char * ptrContiguous;
ptr = new char*[numChannels];
ptrContiguous = new char[x*y*byteSize*nC*nM*nZ*nT];
char * p = ptrContiguous;
for(int i = 0; i < numChannels; i++)
{
ptr[i] = p;
p += x*y*byteSize;
}
現在,如果您使用STL中的向量,您的代碼就變成了這樣:
std::vector<std::string> ptr;
ptr.resize(numChannels);
std::string ptrContiguous;
ptrContiguous.resize(x*y*byteSize*nC*nM*nZ*nT);
const int part_size = x*y*byteSize;
for(int i = 0; i < numChannels; i++)
{
ptr[i] = std::string(ptrContiguous.begin() + i * part_size, ptrContiguous.begin() + (i+1) * part_size);
}
此外, 這個關於矢量和字符串的 鏈接應該可以幫到你。 這是我建議你的代碼,不知道ptrContiguous
的目的是ptrContiguous
。
嘗試這個(為了代碼清晰,重命名了一些變量,使用C風格的內存管理,因為這基本上是C代碼,但是如果你不熟悉malloc
和free
,請告訴我):
char **short_strings; // short_strings[i] is the ith "short string"
char *long_string;
ptr = malloc(sizeof(char*) * num_short_strings);
long_string = malloc(sizeof(char) * num_short_strings * short_string_length);
char *p = long_string;
for(int i = 0; i < num_short_strings; i++)
{
short_strings[i] = p;
p += sizeof(char) * short_string_length;
}
注意,C ++ new
/ delete
和C風格的malloc
和free
都不允許你為short_strings[i]
釋放內存(例如通過調用free(short_strings[i])
或delete[] short_strings[i]
。這是因為這些動態內存分配器以塊的形式分配內存,而free
和delete
只允許你刪除你所分配的整個塊。如果你想能夠單獨刪除短字符串,你需要為每個短字符串重新分配內存,並且strcpy
等
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.