如何在C++中将元素添加到非固定大小的数组中?

How can I add elements to a non-fixed size array in C++?

本文关键字:数组 C++ 添加 元素      更新时间:2023-10-16

如果可能的话,请告诉我如何将元素添加到非固定大小的数组中!
这是我的代码:

#include <iostream>
#include "../Headers/print.h"
#include <string>
using namespace std;
int cells[] = {0};


我想为cells添加更多元素,但我找不到答案,而且我尝试过的所有方法都不起作用......
谢谢!

如何在

C++中将元素添加到非固定大小的数组中?

首先,数组的大小是固定的。您可以跳过在初始化数组时指定大小

,如下所示,
int cells[] = {0};

数组的大小由编译器自动推断。

如果你想要动态大小数组,请使用vector。有关示例,请参阅下面的代码,

#include <iostream>
#include <vector>
int main(){
int cells1[] = {0}, cells2[] = {0,1,2,3,4,5};
std::cout<<"Size of cells1 array: "<<sizeof(cells1)/sizeof(cells1[0])<<std::endl; // 1
std::cout<<"Size of cells2 array: "<<sizeof(cells2)/sizeof(cells2[0])<<std::endl; // 6
std::vector<int> cells3{0}; // Vector - a dynamic array
std::cout<<"Size of cells3 vector: "<<cells3.size()<<std::endl; // 1
cells3.push_back(1); // Append an element to the end of vector
std::cout<<"Size of cells3 vector: "<<cells3.size()<<std::endl; // 2
return 0;
}

输出

Size of cells1 array: 1
Size of cells2 array: 6
Size of cells3 vector: 1
Size of cells3 vector: 2

您可以获得对第一个元素的引用 &cell[0] 加上元素数量乘以它们的大小 + 1 * sizeof(int(,因此您将获得数组后第一个字节的地址。 然后,您可以使用以下方法在此地址分配内存: https://stackoverflow.com/a/19103230/11685627 分配元素的大小(整数(*数量。您应该能够使用您的数组,因为它的大小已扩展。请记住在阵列超出块范围后"释放"内存。 https://learn.microsoft.com/en-gb/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc?redirectedfrom=MSDN https://learn.microsoft.com/en-gb/windows/win32/api/memoryapi/nf-memoryapi-virtualfree Ofc 这是明确的困难方法。