一、使用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/zh-tw/n/286803.html