数组是一种同质数据结构,用于在连续的内存位置中保存相似类型的数据,可以使用基地址和索引进行访问。有很多不同的应用程序中,我们使用数组来保存适用于合适用途的数据。向数组中插入元素是一种繁琐的过程之一。我们可以通过循环从用户那里获取输入来插入它们,或者从文件中插入它们,或者还有其他一些插入它们的方法。初始化数组为特定值(在该数组的所有位置插入该值)也有一些不同的方法。在本文中,我们将看到如何使用C++创建一个大小为n的数组,并在其中的所有位置插入元素k。
理解概念并举例说明
Given array length n = 10, insert k = 5 at every location inside the array. The array A will be like this:
A = [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]
最简单的方法是使用循环将元素k填充到数组中。让我们来看看第一个算法,我们使用for循环将k插入到数组A的每个位置。
算法
取出大小为 n 的数组 A,并插入元素 k
对于索引i从0到n-1,执行以下操作
A[i]:=k
结束循环
返回 A
示例
#include <iostream>
# define Z 30
using namespace std;
void displayArr(int arr[] ) {
for( int i = 0; i < Z; i++ ){
cout << arr[ i ] << ", ";
}
}
void initializeArray( int A[], int k ){
for( int i = 0; i < Z; i++ ){
A[ i ] = k;
}
}
int main() {
int arr[ Z ];
cout << "Initialize array with value 15" << endl;
initializeArray( arr, 15);
cout << "Array elements: " << endl;
displayArr( arr );
}
输出
Initialize array with value 15
Array elements:
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
使用向量构造函数
与静态数组不同,vectors可以用来创建动态数组。要使用某个元素初始化一个vector,我们可以在vector构造函数内使用第二个参数。vector构造函数接受第一个元素作为其大小,第二个元素作为初始化值。让我们看一下代码以便更清楚地理解。
示例
#include <iostream>
#include <vector>
# define Z 30
using namespace std;
void displayArr( vector<int> v ){
for( auto e : v ){
cout << e << ", ";
}
}
int main() {
cout << "initialize vector with 20:" << endl;
vector<int> arr( Z, 20 );
cout << "Array elements: " << endl;
displayArr( arr );
}
输出
initialize vector with 20:
Array elements:
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
结论
在本文中,我们看到了两种使用特定值初始化数组的方法。第一种方法使用静态数组,我们可以使用循环进行赋值。在下一种方法中,使用了动态数组或向量。对于向量,可以使用构造函数进行赋值,但有一个前提条件。数组必须有一些预定义的位置来存储数据。因此,必须提供向量的大小作为第一个参数,然后第二个元素是要放置在向量的每个位置上的关键元素。