如何将元素添加到 C++ 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/755835/
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 17:06:59  来源:igfitidea点击:

How to add element to C++ array?

c++arrays

提问by r4ccoon

I want to add an int into an array, but the problem is that I don't know what the index is now.

我想在数组中添加一个 int,但问题是我现在不知道索引是什么。

int[] arr = new int[15];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;

That code works because I know what index I am assigning to, but what if I don't know the index...

该代码有效,因为我知道我要分配给哪个索引,但是如果我不知道索引怎么办...

In PHP, I can just do arr[]=22;, which will automatically add 22 to the next empty index of the array. But in C++ I can't do that, it gives me a compiler error. What do you guys suggest?

在 PHP 中,我可以只做arr[]=22;,它会自动将 22 添加到数组的下一个空索引。但是在 C++ 中我不能这样做,它给了我一个编译器错误。你们有什么建议?

回答by Mehrdad Afshari

Arrays in C++ cannot change size at runtime. For that purpose, you should use vector<int>instead.

C++ 中的数组在运行时不能改变大小。为此,您应该vector<int>改用。

vector<int> arr;
arr.push_back(1);
arr.push_back(2);

// arr.size() will be the number of elements in the vector at the moment.

As mentioned in the comments, vectoris defined in vectorheader and stdnamespace. To use it, you should:

如评论中所述,vectorvector标头和std命名空间中定义。要使用它,您应该:

#include <vector>

#include <vector>

and also, either use std::vectorin your code or add

而且,std::vector在您的代码中使用或添加

using std::vector; 

or

或者

using namespace std;

after the #include <vector>line.

#include <vector>线。

回答by jab

There is no way to do what you say in C++ with plain arrays. The C++ solution for that is by using the STL library that gives you the std::vector.

没有办法用普通数组来做你在 C++ 中所说的。对此的 C++ 解决方案是使用 STL 库,该库为您提供std::vector.

You can use a vectorin this way:

您可以这样使用 a vector

std::vector< int > arr;

arr.push_back(1);
arr.push_back(2);
arr.push_back(3);

回答by azoundria

You don't have to use vectors. If you want to stick with plain arrays, you can do something like this:

您不必使用向量。如果你想坚持使用普通数组,你可以这样做:

int arr[] = new int[15];
unsigned int arr_length = 0;

Now, if you want to add an element to the end of the array, you can do this:

现在,如果你想在数组的末尾添加一个元素,你可以这样做:

if (arr_length < 15) {
  arr[arr_length++] = <number>;
} else {
  // Handle a full array.
}

It's not as short and graceful as the PHP equivalent, but it accomplishes what you were attempting to do. To allow you to easily change the size of the array in the future, you can use a #define.

它不像 PHP 等价物那样简短优雅,但它完成了您试图做的事情。为了让您将来可以轻松更改数组的大小,您可以使用 #define。

#define ARRAY_MAX 15

int arr[] = new int[ARRAY_MAX];
unsigned int arr_length = 0;

if (arr_length < ARRAY_MAX) {
  arr[arr_length++] = <number>;
} else {
  // Handle a full array.
}

This makes it much easier to manage the array in the future. By changing 15 to 100, the array size will be changed properly in the whole program. Note that you will have to set the array to the maximum expected size, as you can't change it once the program is compiled. For example, if you have an array of size 100, you could never insert 101 elements.

这使得将来管理阵列变得更加容易。通过将 15 改为 100,数组大小将在整个程序中正确更改。请注意,您必须将数组设置为预期的最大大小,因为一旦编译程序就无法更改它。例如,如果您有一个大小为 100 的数组,则永远无法插入 101 个元素。

If you will be using elements off the end of the array, you can do this:

如果您将使用数组末尾的元素,您可以这样做:

if (arr_length > 0) {
  int value = arr[arr_length--];
} else {
  // Handle empty array.
}

If you want to be able to delete elements off the beginning, (ie a FIFO), the solution becomes more complicated. You need a beginning and end index as well.

如果您希望能够从一开始就删除元素(即 FIFO),则解决方案会变得更加复杂。您还需要一个开始和结束索引。

#define ARRAY_MAX 15

int arr[] = new int[ARRAY_MAX];
unsigned int arr_length = 0;
unsigned int arr_start = 0;
unsigned int arr_end = 0;

// Insert number at end.
if (arr_length < ARRAY_MAX) {
  arr[arr_end] = <number>;
  arr_end = (arr_end + 1) % ARRAY_MAX;
  arr_length ++;
} else {
  // Handle a full array.
}

// Read number from beginning.
if (arr_length > 0) {
  int value = arr[arr_start];
  arr_start = (arr_start + 1) % ARRAY_MAX;
  arr_length --;
} else {
  // Handle an empty array.
}

// Read number from end.
if (arr_length > 0) {
  int value = arr[arr_end];
  arr_end = (arr_end + ARRAY_MAX - 1) % ARRAY_MAX;
  arr_length --;
} else {
  // Handle an empty array.
}

Here, we are using the modulus operator (%) to cause the indexes to wrap. For example, (99 + 1) % 100 is 0 (a wrapping increment). And (99 + 99) % 100 is 98 (a wrapping decrement). This allows you to avoid if statements and make the code more efficient.

在这里,我们使用模数运算符 (%) 使索引换行。例如,(99 + 1) % 100 是 0(包装增量)。并且 (99 + 99) % 100 是 98(包装递减)。这使您可以避免使用 if 语句并使代码更高效。

You can also quickly see how helpful the #define is as your code becomes more complex. Unfortunately, even with this solution, you could never insert over 100 items (or whatever maximum you set) in the array. You are also using 100 bytes of memory even if only 1 item is stored in the array.

当您的代码变得更加复杂时,您还可以快速了解 #define 的帮助。不幸的是,即使使用此解决方案,您也永远无法在数组中插入超过 100 个项目(或您设置的任何最大值)。即使数组中只存储了 1 个项目,您也会使用 100 字节的内存。

This is the primary reason why others have recommended vectors. A vector is managed behind the scenes and new memory is allocated as the structure expands. It is still not as efficient as an array in situations where the data size is already known, but for most purposes the performance differences will not be important. There are trade-offs to each approach and it's best to know both.

这是其他人推荐向量的主要原因。一个向量在幕后进行管理,并随着结构的扩展分配新的内存。在数据大小已知的情况下,它仍然不如数组有效,但对于大多数用途,性能差异并不重要。每种方法都需要权衡利弊,最好同时了解这两种方法。

回答by azoundria

Use a vector:

使用向量:

#include <vector>

void foo() {
    std::vector <int> v;
    v.push_back( 1 );       // equivalent to v[0] = 1
}

回答by Brian R. Bondy

int arr[] = new int[15];

The variable arrholds a memory address. At the memory address, there are 15 consecutive ints in a row. They can be referenced with index 0 to 14 inclusive.

该变量arr保存一个内存地址。在内存地址处,有 15 个连续的整数。可以使用索引 0 到 14(含)来引用它们。

In php i can just do this arr[]=22; this will automatically add 22 to the next empty index of array.

在 php 中,我可以这样做 arr[]=22; 这将自动将 22 添加到数组的下一个空索引。

There is no concept of 'next' when dealing with arrays.
One important thing that I think you are missing is that as soon as the array is created, all elements of the array already exist. They are uninitialized, but they all do exist already. So you aren't 'filling' the elements of the array as you go, they are already filled, just with uninitialized values. There is no way to test for an uninitialized element in an array.

处理数组时没有“下一步”的概念。
我认为您缺少的一件重要事情是,一旦创建数组,数组的所有元素就已经存在。它们未初始化,但它们都已经存在。因此,您不会在执行过程中“填充”数组的元素,它们已经被填充,只是带有未初始化的值。无法测试数组中未初始化的元素。

It sounds like you want to use a data structure such as a queueor stackor vector.

听起来您想使用诸如queuestackvector 之类的数据结构。

回答by dirkgently

I fully agree with the vectorway when implementing a dynamic array. However, bear in mind that STL provides you with a host of containers that cater to different runtime requirements.You should choose one with care. E.g: For fast insertion at back you have the choice between a vectorand a deque.

我完全同意vector实现动态数组的方式。但是,请记住,STL 为您提供了大量满足不同运行时要求的容器。您应该谨慎选择。例如:为了在后面快速插入,您可以在 avector和 a之间进行选择deque

And I almost forgot, with great power comes great responsibility :-) Since vectors are flexible in size, they often reallocate automagically to adjust for adding elements.So beware about iterator invalidation (yes, it applies as well to pointers). However, as long as you are using operator[]for accessing the individual elements you are safe.

我差点忘了,能力vector越大责任越大:-) 由于s 的大小灵活,它们经常自动重新分配以调整添加元素。所以要注意迭代器失效(是的,它也适用于指针)。但是,只要您operator[]用于访问各个元素,您就是安全的。

回答by binarybob

I may be missing the point of your question here, and if so I apologize. But, if you're not going to be deleting any items only adding them, why not simply assign a variable to the next empty slot? Every time you add a new value to the array, just increment the value to point to the next one.

我可能在这里遗漏了您的问题,如果是这样,我深表歉意。但是,如果您不打算删除任何项目而只是添加它们,为什么不简单地为下一个空槽分配一个变量呢?每次向数组添加新值时,只需增加该值以指向下一个值。

In C++ a better solution is to use the standard library type std::list< type >, which also allows the array to grow dynamically, e.g.:

在 C++ 中,更好的解决方案是使用标准库 type std::list< type >,它也允许数组动态增长,例如:

#include <list>

std::list<int> arr; 

for (int i = 0; i < 10; i++) 
{
    // add new value from 0 to 9 to next slot
    arr.push_back(i); 
}

// add arbitrary value to the next free slot
arr.push_back(22);

回答by shortwavedave

Initialize all your array elements to null first, then look for the null to find the empty slot

首先将所有数组元素初始化为 null,然后查找 null 以找到空槽

回答by Sad Developer

If you are writing in C++ -- it is a way better to use data structures from standard library such as vector.

如果您使用 C++ 编写 - 使用标准库(例如向量)中的数据结构是一种更好的方法。

C-style arrays are very error-prone, and should be avoided whenever possible.

C 风格的数组非常容易出错,应尽可能避免。

回答by JavaCakes

You can use a variable to count places in the array, so when ever you add a new element, you put it in the right place. For example:

您可以使用变量来计算数组中的位置,因此无论何时添加新元素,都可以将其放在正确的位置。例如:

int a = 0;
int arr[5] = { };
arr[a] = 6;
a++;