动态数组的大小或在不知道大小的情况下循环遍历它
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,
P.S。如果我想使用std::vector
,我不会问它,所以不要告诉我使用它:)
没有。这就是每个人都使用容器的原因之一。如果std::vector不满意,你可以自己做一个容器。
编辑:由于动态数组大小是在运行时确定的,必须有人将大小存储在某处(除非您愿意使用哨兵值)。甚至编译器也无济于事,因为大小是在运行时确定的。
Astd::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]
}
如果您想在其中存储动态数组的大小,那么,just do so:
#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));
}
You can even put that functionality in a libraryesque set of functions! 哦,一旦你这样做了,你就会意识到你可以有一个 unordered_map
将指针映射到大小。但这就像使用 vector
:完全无聊。
如标题所示,我能否以某种方式获取动态分配数组的大小(我不能单独保留它),或者以某种方式循环遍历此数组而不使用它的大小?
int *ar=new int[x]; //x-size of array, I don't know it in the beggining,
P.S。如果我想使用std::vector
,我不会问它,所以不要告诉我使用它:)
没有。这就是每个人都使用容器的原因之一。如果std::vector不满意,你可以自己做一个容器。
编辑:由于动态数组大小是在运行时确定的,必须有人将大小存储在某处(除非您愿意使用哨兵值)。甚至编译器也无济于事,因为大小是在运行时确定的。
Astd::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]
}
如果您想在其中存储动态数组的大小,那么,just do so:
#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));
}
You can even put that functionality in a libraryesque set of functions! 哦,一旦你这样做了,你就会意识到你可以有一个 unordered_map
将指针映射到大小。但这就像使用 vector
:完全无聊。