如何在 C++ 数组的末尾添加一些东西?

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

How to add something at the end of a c++ array?

c++arrays

提问by Angew is no longer proud of SO

I have an array, but I want to add something at the end without overwriting any of the data that is already present it it. It has to be an Array not a vector as it is an Assignment.

我有一个数组,但我想在最后添加一些内容而不覆盖它已经存在的任何数据。它必须是一个数组而不是一个向量,因为它是一个赋值。

回答by Mike Seymour

From the comments, it sounds like you don't want to add to the end of an array, but rather to partially fill an array and keep track of how much data you've written. You just need a variable to keep track of that:

从评论中,听起来您不想添加到数组的末尾,而是部分填充数组并跟踪您写入了多少数据。您只需要一个变量来跟踪它:

char array[10];
size_t size = 0;

// Add characters:
array[size++] = 'H';
array[size++] = 'e';
array[size++] = 'l';
array[size++] = 'l';
array[size++] = 'o';

You need to make sure that you never go beyond the end of the array, otherwise you will corrupt other memory.

您需要确保永远不会超出数组的末尾,否则会损坏其他内存。

回答by Angew is no longer proud of SO

C++ arrays aren't extendable. You either need to make the original array larger and maintain the number of valid elements in a separate variable, or create a new (larger) array and copy the old contents, followed by the element(s) you want to add.

C++ 数组不可扩展。您要么需要使原始数组更大并在单独的变量中保持有效元素的数量,要么创建一个新的(更大的)数组并复制旧内容,然后复制要添加的元素。

回答by CloudyMarble

You can create andother Array which is bigger than the 1st one and copy all elements then add the new element at the end of the array.

您可以创建比第一个更大的其他数组并复制所有元素,然后在数组末尾添加新元素。

alternatively you can convert the array to vector, add an element then convert the vector to array back. Take a look at: How to convert vector to array in C++, What is the simplest way to convert array to vector?

或者,您可以将数组转换为向量,添加一个元素,然后将向量转换回数组。看一看: How to convert vector to array in C++将数组转换为向量的最简单方法是什么?