简体   繁体   English

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

[英]Size of dynamic array or loop through it without knowing size

Like in title, can I somehow get size of dynamic allocated array (I can't keep it separately), or somehow loop through this array without using it's size? 就像标题中一样,我可以以某种方式获取动态分配数组的大小(我不能单独保存它),还是以某种方式在不使用其大小的情况下循环遍历该数组?

int *ar=new int[x]; //x-size of array, I don't know it in the beggining, 

PS If I wanted to use std::vector , I wouldn't ask about it, so don't tell me to use it :) PS:如果我想使用std::vector ,我不会问这个,所以不要告诉我使用它:)

A std::vector is designed for this. 为此设计了 一个 std::vector

If you can't use a std::vector I can see a couple of options. 如果您不能使用std::vector我可以看到几个选项。

1) Use an array terminator. 1)使用数组终止符。

If your array should only contain positive numbers (for example) or numbers within a given range then you can use an illegal value (eg -1) as an array terminator. 如果您的数组仅应包含正数(例如)或给定范围内的数字,则可以使用非法值(例如-1)作为数组终止符。

for(int* i = arr; *i != -1; ++i)
{
    // do something with *i
}

2) Embed the length in the array. 2)将长度嵌入数组中。

For a numeric array you could, by convention, store its length in the first element. 对于数字数组,按照惯例,您可以将其长度存储在第一个元素中。

for(int i = 0; i < arr[0]; ++i)
{
    // do something with arr[i + 1]
}

No. That's one reason everybody uses containers. 不,这是每个人都使用容器的原因之一。 If std::vector doesn't please you, you can make a container of your own. 如果std :: vector不令人满意,您可以自己制作一个容器。

Edit: Since dynamic array size is determined at runtime, someone must store the size somewhere (unless you're willing to use a sentry value). 编辑:由于动态数组的大小是在运行时确定的,因此必须有人将大小存储在某个地方 (除非您愿意使用哨兵值)。 Not even the compiler can help, because the size is determined in runtime. 甚至编译器也无济于事,因为大小是在运行时确定的。

If you want to store the size your dynamic array inside it, well, 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! 您甚至可以将该功能放入一组库式功能中! Oh, and once you do that you realize you could just have an unordered_map that maps pointers to sizes. 哦,一旦这样做,您就会意识到您可以拥有一个unordered_map来将指针映射到大小。 But that would be like using vector : Totally boring. 但这就像使用vector :完全无聊。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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