一、使用vector容器
在C++中,可以使用vector容器来实现数组元素的添加功能。vector是一个动态数组,多用于STL中。相较于普通数组,vector容器具有易于使用、自动扩容等特点。
要使用vector容器,需要包含头文件<vector>。
#include <vector>
int main()
{
std::vector myVector; //创建一个初始为空的vector
myVector.push_back(1); //向vector中添加元素
myVector.push_back(2);
myVector.push_back(3);
//输出vector中的元素
for(auto iter=myVector.begin(); iter!=myVector.end(); iter++)
{
std::cout << *iter << " ";
}
return 0;
}
在上面的代码中,使用push_back()函数向vector中添加元素。需要注意的是,vector不支持随机访问,因此需要使用迭代器来遍历vector中的元素。
二、使用普通数组和指针实现添加元素
另一种实现数组添加元素的方法是使用普通数组和指针。在这种实现方式中,需要首先创建一个长度为n的数组,然后对数组进行扩容操作,并将扩容后的新数组指针赋给原数组指针。
int main()
{
int n=5, i;
int *a = new int[n];
//向数组中添加元素
for(i=0; i<n; i++)
{
a[i] = i+1;
}
//输出原数组中的元素
for(i=0; i<n; i++)
{
std::cout << a[i] << " ";
}
//进行扩容操作
int *temp = new int[n+1];
for(i=0; i<n; i++)
{
temp[i] = a[i];
}
temp[n] = 6; //向扩容后的数组中添加元素
n++; //更新数组长度
delete[] a; //释放原数组内存
a = temp; //将扩容后的数组指针赋给原数组指针
//输出扩容后的数组中的元素
for(i=0; i<n; i++)
{
std::cout << a[i] << " ";
}
delete[] a; //释放扩容后的数组内存
return 0;
}
需要注意的是,在使用这种方法添加元素时,需要进行数组扩容操作,并释放原数组内存,将新数组指针赋给原数组指针。
三、使用动态内存分配实现添加元素
还有一种添加元素的方法是使用new运算符动态分配内存。使用new分配数组内存时,相比于上一种方法,不需要手动进行数组的扩容和释放内存操作。
int main()
{
int n=5, i;
int *a = new int[n];
//向数组中添加元素
for(i=0; i<n; i++)
{
a[i] = i+1;
}
//输出原数组中的元素
for(i=0; i<n; i++)
{
std::cout << a[i] << " ";
}
//使用new动态分配内存
int *temp = new int[n+1];
for(i=0; i<n; i++)
{
temp[i] = a[i];
}
temp[n] = 6; //向新数组中添加元素
n++; //更新数组长度
delete[] a; //释放原数组内存
a = temp; //将新数组指针赋给原数组指针
temp = nullptr; //释放新数组指针
//输出添加元素后的数组中的元素
for(i=0; i<n; i++)
{
std::cout << a[i] << " ";
}
delete[] a; //释放数组内存
return 0;
}
需要注意的是,使用new运算符动态分配内存时,需要手动释放内存,防止内存泄漏。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/286803.html