如何在C++中将元素添加到非固定大小的数组中?
How can I add elements to a non-fixed size array in C++?
如果可能的话,请告诉我如何将元素添加到非固定大小的数组中!
这是我的代码:
#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 这是明确的困难方法。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '