[英]How to write a procedure to modify the elements and size of a dynamic array without knowing the size?
[英]Size of dynamic array or loop through it without knowing size
就像標題中一樣,我可以以某種方式獲取動態分配數組的大小(我不能單獨保存它),還是以某種方式在不使用其大小的情況下循環遍歷該數組?
int *ar=new int[x]; //x-size of array, I don't know it in the beggining,
PS:如果我想使用std::vector
,我不會問這個,所以不要告訴我使用它:)
為此設計了 一個 std::vector
。
如果您不能使用std::vector
我可以看到幾個選項。
1)使用數組終止符。
如果您的數組僅應包含正數(例如)或給定范圍內的數字,則可以使用非法值(例如-1)作為數組終止符。
for(int* i = arr; *i != -1; ++i)
{
// do something with *i
}
2)將長度嵌入數組中。
對於數字數組,按照慣例,您可以將其長度存儲在第一個元素中。
for(int i = 0; i < arr[0]; ++i)
{
// do something with arr[i + 1]
}
不,這是每個人都使用容器的原因之一。 如果std :: vector不令人滿意,您可以自己制作一個容器。
編輯:由於動態數組的大小是在運行時確定的,因此必須有人將大小存儲在某個地方 (除非您願意使用哨兵值)。 甚至編譯器也無濟於事,因為大小是在運行時確定的。
如果要在其中存儲動態數組的大小, 請這樣做 :
#include <iostream>
#include <cstdint>
#include <cstddef>
using std::size_t;
struct head_t { size_t size; int data[]; };
int main() {
head_t* h = static_cast<head_t*>(::operator new(sizeof(head_t) + 10 * sizeof(int)));
h->size = 10;
int* my_10_ints = h->data;
// Oh noez! I forgot 10!
size_t what_was_10_again = static_cast<head_t*>(static_cast<void*>(my_10_ints) - offsetof(head_t, data))->size;
::std::cout << what_was_10_again << "\n";
::operator delete(static_cast<void*>(my_10_ints) - offsetof(head_t, data));
}
您甚至可以將該功能放入一組庫式功能中! 哦,一旦這樣做,您就會意識到您可以擁有一個unordered_map
來將指針映射到大小。 但這就像使用vector
:完全無聊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.