【问题标题】:How to apply range based loop to array of arrays in C++11?如何将基于范围的循环应用于 C++11 中的数组数组?
【发布时间】:2014-01-28 15:30:15
【问题描述】:
#include <iostream>
using namespace std;

int main(){
    int arr[4] = {1,2,3,4};
    int arr2[4] = {5,6,7,8};
    int **arrPtr;

    arrPtr[0] = arr;
    arrPtr[1] = arr2;

    for (int *a : arrPtr ){
        for (int i : a){
            cout << i << endl;
        }
    }
}

我知道这个实现不是要走的路,而是在最后展示意图。基本上我正在尝试打印由另一个双指针列出的数组的内容。 有什么办法可以让这段代码工作吗?

【问题讨论】:

  • 那不是数组数组,那只是错误的代码。 *arrPtr 没有指向任何地方,因此分配给它是非法的。
  • 您希望输出 8 行 (4 + 4) 还是 16 (4 * 4)?另外,您知道范围适用于数组吗? for (int a : arr){cout &lt;&lt; a &lt;&lt; endl;} 会给你1 2 3 4 没有指针
  • 我只是尝试学习c++11不多并修改一些指针...我只是尝试打印出彼此下方的所有项目

标签: arrays pointers c++11 foreach


【解决方案1】:
#include <iostream>

int main() {
    int m[][4] = {
                    { 0, 1, 2, 3 },
                    { 4, 5, 6, 7 },
                    { 8, 9, 0, 1 },
                    { 2, 3, 4, 5 },
                 };

    for(auto &line : m) {
        for(auto &value : line) {
            std::cout << value << ' ';
        }
        std::cout << std::endl;
    }
}

http://coliru.stacked-crooked.com/a/d603241402fcc886

奖金

请注意,这也有效:

#include <iostream>

int main() {
    for(auto &line : (int [][4])
            {
                { 0, 1, 2, 3 },
                { 4, 5, 6, 7 },
                { 8, 9, 0, 1 },
                { 2, 3, 4, 5 },
            }) {
        for(auto &value : line) {
            std::cout << value << ' ';
        }
        std::cout << std::endl;
    }
}

【讨论】:

  • 感谢您的回答,您能解释一下自动和引用是什么吗?
  • @Erogol 它是 c++11 类型推导功能,因此当编译器应该已经弄清楚这一点时,您无需明确说明类型。你在问编译器:你知道它是什么类型,所以我想要那种类型的 linevalue。使用引用变量 (auto &) 是必要的,因为没有它,line 将只是一个没有数组大小信息的指针,这是 range-for 所必需的。检查这个:stackoverflow.com/questions/20982514/…
【解决方案2】:

新的 range-for 循环不适用于原始指针类型,因为它们不包含大小信息。如果您在编译时知道它们的长度,则可以将它们转换为指向数组的指针并在 range-for 中使用。这样的代码可能很好玩,但实际使用时请使用std::arraystd::vector

#include <iostream>
#include <memory>
using namespace std;

int main(){
    int arr[4] = {1,2,3,4};
    int arr2[4] = {5,6,7,8};
    unique_ptr<int*[]> arrPtrHolder(new int*[2]);
    int **arrPtr = arrPtrHolder.get();

    arrPtr[0] = arr;
    arrPtr[1] = arr2;

    for (int *a : *(int*(*)[2])(arrPtr)){
        for (int i : *(int (*)[4])(a)){
            cout << i << endl;
        }
    }
}

http://coliru.stacked-crooked.com/a/a207f5c4853b1e1f

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 2013-04-01
    相关资源
    最近更新 更多