整数数组长度 C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/683838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:43:34  来源:igfitidea点击:

Int Array Length C++

c++arrays

提问by UncleZeiv

I have to use a dynamic length int array in my program, and want to be able to get the number of objects in it at various points in my code. I am not that familiar with C++, but here is what I have. Why is it not giving me the right length? Thanks.

我必须在我的程序中使用动态长度 int 数组,并且希望能够在我的代码中的各个点获取其中的对象数量。我对 C++ 不太熟悉,但这是我所拥有的。为什么它没有给我合适的长度?谢谢。

<#include <iostream>
Using Namespace std;
int length(int*);


void main()
{
  int temp[0];
  temp[0] = 7;
  temp [1] = 10;
  temp[2] = '
#include <iostream>
#include <vector>
using namespace std;
int length(int*);


int main ()  //  error: ‘::main' must return ‘int'
{
    int temp[3];
    temp[0] = 7;
    temp[1] = 10;
    // don't use char constants for int values without reason
    temp[2] = 0; 

    cout << length(temp) << endl;

    vector<int> vec_temp;

    vec_temp.push_back(7);
    vec_temp.push_back(10);

    cout << vec_temp.size() << endl;

}

int length(int* temp)
{
    int i = 0;
    int count = 0;

    while (*(temp + i) != 0) // *temp + i == (*temp) + i
    {
          count++;
          i++; // don't really need both i and count
    }
    return count;
}
'; cout << length(temp) << endl; } int length(int* temp) { int i = 0; int count = 0; while (*temp + i != '
int length(int* temp)
{
    int count = 0;

    while (*temp != 0)
    {
          ++count;
          ++temp;
    }

    return count;
}
') { count++; i++; } return count; }

currently it just goes into an endless loop ;_;

目前它只是进入一个无限循环;_;

回答by Pete Kirkham

In C++ arrays are not dynamic. Your temp array has zero length, and attempting to write to members beyond its length is undefined behaviour. It's most likely not working as it will be writing over some part of the stack.

在 C++ 中,数组不是动态的。您的临时数组长度为零,尝试写入超出其长度的成员是未定义的行为。它很可能不起作用,因为它将写入堆栈的某些部分。

Either create a fixed size array with enough space to put everything you want to in it, or use a std::vector<int>which is a dynamic data structure.

要么创建一个具有足够空间的固定大小的数组来放置您想要的所有内容,要么使用std::vector<int>动态数据结构。

int length(int* temp)
{
    int count = 0;

    while (temp[count] != 0)
          ++count;

    return count;
}

For the vector, there's no need to specify the size at the start, and you can put a zero in, and finding the length is a simple operation rather than requiring a loop.

对于向量,不需要在开始时指定大小,您可以在其中输入零,并且找到长度是一个简单的操作,而不需要循环。

Another bug inside your loop was that you were looking at the first member of the array and adding i to that value, rather than incrementing the pointer by i. You don't really need both i and count, so could write that a couple of other ways, either incrementing temp directly:

循环中的另一个错误是您正在查看数组的第一个成员并将 i 添加到该值,而不是将指针增加 i。你真的不需要 i 和 count,所以可以写其他几种方式,或者直接增加 temp:

int temp[0];

or using count to index temp:

或使用计数来索引温度:

while (*temp + i != '
while (*(temp + i) != '
#include <vector>
#include <iostream>

void print(std::vector<int> const& vec)
{
    using namespace std;

    for (size_t i = 0; i < vec.size(); i++)
    {
        cout << vec[i] << " ";
    }

    cout << endl;
}

int main()
{
    std::vector<int> temp;
    temp.push_back(7);
    temp.push_back(10);

    print(temp);

    return 0;
}
')
')

回答by Andrew Grant

This approach is a bad idea for a couple of reasons, but first here's some problems:

由于几个原因,这种方法是一个坏主意,但首先这里有一些问题:

while (*(temp + i) != '
#include <vector>
#include <iostream>

int main()
{    
    std::vector<int> v;
    v.push_back(7);
    v.push_back(10);
    std::cout << v.size() << std::endl;
    return 0;
}
')

This is an array of 0 items, which I don't even think is permitted for stack elements. When declaring an array like this you must specify the maximum number of values you will ever use: E.g. int temp[10];

这是一个包含 0 个项目的数组,我什至认为堆栈元素不允许这样做。在声明这样的数组时,您必须指定将使用的最大值数:例如int temp[10];

This is super important!- if you do specify a number less (e.g. [10] and you use [11]) then you will cause a memory overwrite which at best crashes and at worst causes strange bugs that are a nightmare to track down.

这个超级重要!- 如果你确实指定了一个更少的数字(例如 [10] 并且你使用了 [11]),那么你将导致内存覆盖,最好的情况是崩溃,最坏的情况会导致奇怪的错误,这些错误是追查的噩梦。

The next problem is this line:

下一个问题是这一行:

#include <iostream>
using namespace std;

int main () {
    int vet[] = {1,2,3,4,5,6};
    cout << (sizeof (vet) / sizeof *(vet)) << endl;
    return 0;
}

That this line does is take the value stores in the address specified by 'temp' and add i. What you want is to get the value at nth element of the address specified by temp, like so:

这一行的作用是获取存储在 'temp' 指定地址中的值并添加 i。您想要的是获取 temp 指定的地址的第 n 个元素处的值,如下所示:

int temp[256];
int len = sizeof (temp) / sizeof (temp[0]);
// len == 256 * 4 / 4 == 256 on many platforms.

So that's what's wrong, but you should take five minutes to think about a better way to do this.

这就是问题所在,但您应该花五分钟时间思考一个更好的方法来做到这一点。

The reasons I mentioned it's a bad idea are:

我提到这是一个坏主意的原因是:

  • You need to iterate over the entire array anytime you require its length
  • You can never store the terminating element (in this case 0) in the array
  • 您需要在需要其长度的任何时候遍历整个数组
  • 您永远不能将终止元素(在本例中为 0)存储在数组中

Instead I would suggest you maintain a separate value that stores the number of elements in the array. A very common way of doing this is to create a class that wraps this concept (a block of elements and the current size).

相反,我建议您维护一个单独的值来存储数组中的元素数。一个非常常见的方法是创建一个包含这个概念的类(元素块和当前大小)。

The C++ standard library comes with a template class named "vector" which can be used for this purpose. It's not quite the same as an array (you must add items first before indexing) but it's very similar. It also provides support for copying/resizing which is handy too.

C++ 标准库带有一个名为“vector”的模板类,可用于此目的。它与数组并不完全相同(您必须在索引之前先添加项目)但它非常相似。它还提供对复制/调整大小的支持,这也很方便。

Here's your program written to use std::vector. Instead of the 'length' function I've added something to print out the values:

这是您编写的使用 std::vector 的程序。我添加了一些东西来打印值,而不是 'length' 函数:

int* temp = new int[256];
int len = sizeof (temp) / sizeof (temp[0]);
// len == 4 / 4 == 1 on many platforms.

回答by Reunanen

You could try:

你可以试试:

  *temp + i

Your current solution is calculating temp[0] + i(equals 7+i), which apparently is not what you want.

您当前的解决方案是计算temp[0] + i(equals 7+i),这显然不是您想要的。

回答by UncleZeiv

Not only C++ arrays are not dynamic as Pete points out, but only strings (char *) terminate with '\0'. (This is not to say that you can't use a similar convention for other types, but it's rather unusual, and for good reasons: in particular, relying on a terminator symbol requires you to loop through an array to find its size!)

不仅 C++ 数组不是像 Pete 指出的那样动态,而且只有字符串 (char *) 以 '\0' 终止。(这并不是说你不能对其他类型使用类似的约定,但它很不寻常,并且有充分的理由:特别是,依赖终止符需要你遍历数组来找到它的大小!)

In cases like yours it's better to use the standard library.

在像您这样的情况下,最好使用标准库。

  *(temp + i)

回答by Artur

If you don't want to use std::vector, try this:

如果你不想使用 std::vector,试试这个:

int n;
cin>>n;
int array = new int[n];
int array_length=n;

回答by Dan Olson

The most common way to get the size of a fixed-length array is something like this:

获取固定长度数组大小的最常见方法是这样的:

  temp [1] = 10;
  temp[2] = '
int myarr [] = {1, 2, 3, 4, 5};
int length = sizeof(myarr) / sizeof(myarr[0]);
cout << length;
';

This doesn't work for dynamic arrays because they're actually pointers.

这不适用于动态数组,因为它们实际上是指针。

##代码##

For a dynamic-length array if you care about the size, you're best off storing it somewhere when you allocate the array.

对于动态长度数组,如果您关心大小,则最好在分配数组时将其存储在某处。

The problem with your loop, as pointed out by many is that you have an operator precedence problem here:

正如许多人所指出的,你的循环的问题是你在这里有一个运算符优先级问题:

##代码##

should be:

应该:

##代码##

But the bigger problem, also pointed out above, is that you don't appear to understand pointers versus fixed-length arrays and are writing off the end of your array.

但是,上面也指出的更大的问题是,您似乎不理解指针与固定长度数组的区别,并且正在注销数组的末尾。

回答by Mastermind

If you want to use array properly, you have to allocate enough memory for storing values. Once you specified its length, you can't change it. To know array size, you should store it in variable e.g.:

如果要正确使用数组,则必须分配足够的内存来存储值。一旦你指定了它的长度,你就不能改变它。要知道数组大小,您应该将其存储在变量中,例如:

##代码##

If you want to change array's length, best way is to use std container, for example std::vector.

如果要更改数组的长度,最好的方法是使用 std 容器,例如 std::vector。

回答by jalf

Because you only allocate space for an array of zero elements. The following lines

因为您只为零元素数组分配空间。以下几行

##代码##

do not allocate more memory or resize the array. You are simply writing data outside the array, corrupting some other part of the application state. Don't do that. ;)

不要分配更多内存或调整数组大小。您只是在数组外写入数据,破坏了应用程序状态的其他部分。不要那样做。;)

If you want a resizable array, you can use std::vector (and use the push_back member function to insert new values)

如果你想要一个可调整大小的数组,你可以使用 std::vector (并使用 push_back 成员函数插入新值)

A vector also has the size() member function which tells you the current size.

向量也有 size() 成员函数,它告诉你当前的大小。

If you want to use the primitive array, you have to track the size yourself. (and, when resizing the array is necessary, copy all elements from the old array to the new, larger one)

如果要使用原始数组,则必须自己跟踪大小。(并且,当需要调整数组大小时,将旧数组中的所有元素复制到新的更大的数组中)

回答by dmckee --- ex-moderator kitten

To get dynamic behavior in arrays, use a std::vector, or fall back on the old school c style using int *with manual memory allocation (newand delete)[*]

要在数组中获得动态行为,请使用 a std::vector,或者使用int *手动内存分配(newdelete)[*]

[*] C implementations (discussed in the context of character arrays as C dynamic string length) used malloc, realloc, and free, but these should be avoided in c++ code.

[*] C实现(在字符数组作为的上下文中讨论时的动态字符串长度使用)mallocreallocfree,但这些应在C ++代码来避免。

回答by Artashes Soghomonian

Here is the answer to your question

这是你问题的答案

##代码##