简体   繁体   English

基于多维std :: array的范围

[英]Range based for with multi-dimensional std::array

Tried looking around for this but only found examples using built in array not std::array obj. 试图四处寻找,但仅使用内置数组而不是std :: array obj找到了示例。

// array arr of size 5
array< array<int, 10>, 10> arr = { 0 };

srand((unsigned)time(0));

// initialize elements
for ()
{
    for()
    {
        item = rand() % 100 + 1;
    }
}

basic example trying to initialize 2D array obj to random values. 尝试将2D数组obj初始化为随机值的基本示例。 im not sure what to put between the () of the for loops 我不确定在for循环的()之间放置什么

auto& comes in handy here. auto&在这里派上用场。 Well, the first range-for loop will take on references to each array in the array. 好吧,第一个range-for循环将引用数组中的每个数组。 the second takes on references to each element in the innermost array. 第二个引用最内层数组中的每个元素。 Like: 喜欢:

// initialize elements
for (auto& inner : arr)
{
    for(auto& item : inner)
    {
        item = rand() % 100 + 1;
    }
}

instead of using range based for loops, you can even use functions 而不是使用基于范围的循环,甚至可以使用函数

std::for_each(arr.begin(), arr.end(), [](array<int, 10> const& inner) {
    auto generator = []() { return rand() % 100 + 1; };
    std::generate(inner.begin(), inner.end(), generator);
}
#include <array>
using namespace std;

// array arr of size 5
array< array<int, 10>, 10> arr;

int main() {
  // initialize elements
  for (auto & outer_array : arr)  
  {
      for(auto & inner_array : outer_array)
      {

      }
  }
}

live: https://godbolt.org/g/6eLgBk 直播: https//godbolt.org/g/6eLgBk

for(int i = 0; i < arr.size() ; i++)
{
   for(int j = 0; j < arr[i].size() ; j++)
   {
        arr[i][j] = rand() % 100 + 1;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM