【问题标题】:A method to assign the same value to all elements in an array为数组中的所有元素分配相同值的方法
【发布时间】:2011-12-07 20:10:15
【问题描述】:

我有一个包含 50 个元素的数组

int arr[50];

我想将所有元素设置为相同的值。我该怎么做?

【问题讨论】:

  • 数组是指std::vector
  • 请显示一些代码。目前我们不知道您所说的 array 是什么意思,它可能是std::vectorstd::arraychar[50] 等。

标签: c++ arrays


【解决方案1】:

无论您使用哪种数组,如果它提供迭代器/指针,您都可以使用 <algorithm> 标头中的 std::fill 算法。

// STL-like container:
std::fill(vect.begin(), vect.end(), value);

// C-style array:
std::fill(arr, arr+elementsCount, value);

(其中value 是您要分配的值,elementsCount 是要修改的元素数)

并不是说手动实现这样的循环会那么困难......

// Works for indexable containers
for(size_t i = 0; i<elementsCount; ++i)
    arr[i]=value;

【讨论】:

  • +1 最佳答案,无论他使用什么,因为即使自定义数组类也可以实现迭代器,std::fill 允许灵活地为元素范围分配值。
【解决方案2】:

使用std::vector

std::vector<int> vect(1000, 3); // initialize with 1000 elements set to the value 3.

【讨论】:

  • +1,但 Matteo 的答案更好,因为您的答案仅适用于初始化。
【解决方案3】:

如果必须使用数组,可以使用for 循环:

int array[50];

for (int i = 0; i < 50; ++i)
    array[i] = number; // where "number" is the number you want to set all the elements to

或者作为快捷方式,使用std::fill

int array[50];

std::fill(array, array + 50, number);

如果你想设置所有元素的数字是0,你可以做这个快捷方式:

int array[50] = { };

或者如果你在谈论std::vector,有一个构造函数可以获取向量的初始大小以及每个元素的设置:

vector<int> v(50, n); // where "n" is the number to set all the elements to.

【讨论】:

    【解决方案4】:
    for(int i=0;i<sizeofarray;i++)
    array[i]=valuetoassign
    
    using method
    
    
    void func_init_array(int arg[], int length) {
      for (int n=0; n<length; n++)
       arg[n]=notoassign
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 2012-01-26
      • 2019-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多