繁体   English   中英

动态数组的大小或在不知道大小的情况下循环遍历

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM