c++初始化数组的函数
时间: 2023-12-16 22:02:28 浏览: 47
在 C++ 中,可以使用以下语法来初始化数组:
1. 在声明数组时直接赋值:例如,int arr[] = {1, 2, 3, 4, 5};
2. 使用循环为数组赋值:例如,
```c++
int arr[5];
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
```
3. 使用数组初始化器:例如,int arr[] = {1, 2, 3, 4, 5};
C++ 还提供了一些库函数来初始化数组,例如 `memset` 和 `fill`。`memset` 函数可以用来将数组中的元素设置为指定的值,例如:
```c++
int arr[5];
memset(arr, 0, sizeof(arr)); // 将数组的所有元素设置为0
```
`fill` 函数可以用来将数组中的元素设置为指定的值,例如:
```c++
int arr[5];
fill(arr, arr + 5, 0); // 将数组的所有元素设置为0
```
其中,`arr + 5` 表示指向数组最后一个元素后面一个位置的指针。
相关问题
c++初始化数组内容
在C++中,有几种方法可以初始化数组内容:
1. 使用花括号 {} 初始化器
```cpp
int arr[5] = {1, 2, 3, 4, 5};
```
2. 使用循环语句进行初始化
```cpp
int arr[5];
for(int i = 0; i < 5; i++) {
arr[i] = i + 1;
}
```
3. 使用std::fill函数进行初始化
```cpp
#include <algorithm>
int arr[5];
std::fill(arr, arr + 5, 0); // 将数组的所有元素初始化为0
```
4. 使用std::generate函数进行初始化
```cpp
#include <algorithm>
#include <random>
int arr[5];
std::default_random_engine generator; // 随机数生成器
std::uniform_int_distribution<int> distribution(1, 10); // 生成1到10之间的随机整数
auto rand = std::bind(distribution, generator); // 定义一个返回随机整数的函数
std::generate(arr, arr + 5, rand); // 将数组的所有元素初始化为随机数
```
c++初始化数组为无穷大
在 C++ 中,我们可以使用 std::numeric_limits<T>::infinity() 函数来初始化一个数组为无穷大。
例如,如果我们想要初始化一个 double 类型的数组 arr,可以这样写:
```c++
#include <limits>
#include <iostream>
int main() {
int n = 10;
double arr[n];
// 将 arr 数组初始化为无穷大
for (int i = 0; i < n; i++) {
arr[i] = std::numeric_limits<double>::infinity();
}
// 打印 arr 数组的值
for (int i = 0; i < n; i++) {
std::cout << arr[i] << " ";
}
return 0;
}
```
输出结果如下:
```
inf inf inf inf inf inf inf inf inf inf
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)