C++ specify array indexes in initializer, like C

后端 未结 3 649
余生分开走
余生分开走 2021-01-17 12:18

I used C before (embedded stuff), and I can initialize my arrays like that:

int widths[] = { [0 ... 9] = 1, [10 ... 99] = 2, [100] = 3 };

i

相关标签:
3条回答
  • 2021-01-17 12:42

    No, it is not possible to do it in C++ like that. But you can use std::fill algorithm to assign the values:

    int widths[101];
    fill(widths, widths+10, 1);
    fill(widths+10, widths+100, 2);
    fill(widths+100, widths+101, 3);
    

    It is not as elegant, but it works.

    0 讨论(0)
  • 2021-01-17 12:43

    After years, I tested it just by chance, and I can confirm that it works in g++ -std=c++11, g++ version is 4.8.2.

    0 讨论(0)
  • 2021-01-17 12:55

    hm, you should use std::fill_n() for that task...

    as stated here http://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html the designated inits (extention) are not implemented in GNU C++

    edit: taken from here: initialize a const array in a class initializer in C++

    as a comment said, you can use std:vector to get the result desired. You could still enforce the const another way around and use fill_n.

    int* a = new int[N];
    // fill a
    
    class C {
      const std::vector<int> v;
    public:
      C():v(a, a+N) {}
    };
    
    0 讨论(0)
提交回复
热议问题