如何设置初始化相同的值 [英] how to set initialize same value

查看:65
本文介绍了如何设置初始化相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在此语句中将初始值设置为所有值
int * Array = new int [X];

how to set initialize same value to all value in this statment
int *Array = new int[X];

推荐答案

使用名为memset的函数.
memset(array,value,len)
Use the function named memset.
memset(array, value, len)


语言本身没有这样的东西(为什么拥有它,您总是可以自己做呢?所以语言功能将是多余的) .因此,您只需要编写一个循环并初始化代码中的所有元素即可.

基本上,无论您做什么,这都是在幕后总是发生的事情.您可以使用<algorithm>中的std::fill:
There is not such thing in the language itself (why having it, it you can always do it by yourself? so the language feature would be redundant). So, you just need to write a loop and initialize all the elements in code.

Basically, whatever you do, this is what will always happen under the hood. You can use std::fill from <algorithm>:
#include <algorithm>

//...

const int X = //... // array size
const int someValue = //...
int Array[X]; // or allocate it on heap as you already did
std::fill(Array, Array + X, someValue); // this is not obvious,
//but it will create iterators from your arrays
// and pass then to the function



请参阅: http://www.cplusplus.com/reference/algorithm/fill/ [ ^ ].

—SA



Please see: http://www.cplusplus.com/reference/algorithm/fill/[^].

—SA


除了SAK的解决方案外,您还可以初始化静态定义的数组,如下所示:
In addition to the solution by SAK, you can initialize a statically defined array like that:
int A[10] = {1,1,1,1,1,1,1,1,1,1};


此代码使用列表中提供的常量初始化数组的元素.此列表可能没有比数组更多的元素,但可能会更短:


This code initializes the elements of the array with the constants provided in the list. This list may not have more elements than the array, but it may be shorter:

int A[10] = {1,1,1};


此代码使用值{1,1,1,0,0,0,0,0,0,0}初始化数组.请注意,您未明确分配的元素将自动初始化为0.

如果您的目的是将整个数组初始化为0,则可以这样操作:


This code initializes the array with the values {1,1,1,0,0,0,0,0,0,0}. Note that the elements that you don''t explicitely assign will be automatically intialized with 0.

If your purpose is to intialize the entire array with 0, you can do this like that:

int A[10] = {0};



请注意,这种初始化仅适用于静态数组,不适用于动态分配的数组.但是,标准模板库(STL)中的容器提供了各种构造函数,可让您做到这一点.例如,您可以使用std :: vector创建一个由10个元素组成的矢量,这些矢量被初始化为7:



Note that this kind of intialization only works with static arrays, not dynamically allocated ones. However, the containers in the Standard Template Library (STL) provide various constructors that let you do just that. You could for instance use std::vector to create a vector of 10 elements that are initialized to 7:

#include <vector>
int main() {
   std::vector<int> A(10, 7);
   // do some stuff ...
   return 0;
}


这篇关于如何设置初始化相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆