As I understand it, according to the standard, only the first element of the array is filled, and the rest should be filled with zeros.

int ar[10] = {-1}; int ar2[10][10] = {-1,}; 

Is it possible to somehow set the default value not equal to zero for all elements of the array at the moment of declaration? Maybe there is something in the new standard? Or just a cycle?

  • Interesting. But VS doesn't work. That's exactly what I expected to find. So, in theory, nothing new has been added to the standard. - manking
  • one
    @manking, well, I don’t know how in the general case, but for int a[] (I think in Windows for short) you can get out in crosses int a [5] = {(wmemset ((wchar_t *) a, 1, sizeof (a) / sizeof (a [0])), 1)}; for (int i = 0; i <5; i ++) cout << a [i]; // yes, displays 5 ones - avp

4 answers 4

In C (at least gcc (This is a GNU extension)) you can

 int a[] = { [0 ... 19] = 1} 

etc. (see for example, 5.20 Designated Initializers )
and in C ++ it seems not.

  • one
    With these extensions can be in the pros . - αλεχολυτ

In C ++, you are not using native arrays, but STL containers.

For them, such initialization is available:

 vector<int> vec(5, 42); 

initializes the vector with five values ​​of 42: http://ideone.com/nOTYv9


In addition to the excellent @jfs answer, if speed initialization is important, you can use the usual metaprogramming:

1) we write the generator utility ( generate.cpp )

 #include <cstdlib> #include <iostream> using namespace std; void main(int argc, int* argv[]) { auto val = argv[1]; auto count = atoi(argv[2]); for (int i = 1; i < count; i++) cout << val << "," << endl; cout << val << endl; } 

2) Use it in the project:

 generate 42 5 >arrinit.h 

3) Refer to the code:

  int[] arr = { #include "arrinit.h" }; 
  • 2
    @avp: Well, the order and the work is probably here and now, so you still have to master Linux in your free time. --- Yes, and C ++ is probably not the best choice. - VladD
  • one
    On the other hand, in Windows you can use g ++ (although if at work there is a rule to write for VS ...). Okay, let him think. - avp
  • one
    @jfs: A programmer who makes a mistake in such a cycle is professionally unfit, so it does not have the right to be a serious argument. Writing a loop or using a library function is a matter of code readability and ease of its modification, that is, essentially coding standards adopted in a specific development team. - VladD
  • one
    @jfs: Everybody is wrong - this is yes, but you can make a mistake in calling the library function, so again not an argument. To say out loud "I will not write a trivial cycle, I will call a library function" - especially if such functions in a team are not idiomatic - posturing and narcissism, dangerous for development. Code std::fill_n(arr, _countof(arr), 42); for me personally less readable than a direct loop. But it is necessary to focus not on personal tastes, but on the standard adopted in the team. - VladD
  • 2
    @jfs: It would be self-adoring to write code that is incomprehensible to the team, but more “cool”, since it pleases only the programmer's ego, but does not contribute to a good team-wide result. (With a cycle on an int counter, you have noticed well, but I hope the compiler will notice and issue a warning about the comparison signed and unsigned.) - VladD

@VladD showed two good options:

  • use C ++ containers, such as vector , that support such initialization
  • call std::fill_n() / std::fill() - if just a regular array is needed, then this is the preferred option.

Until performance measurements show that array initialization is a bottleneck in the program, other options may not be considered.

As an unreasonable option, you can initialize the array at compile time using templates :

 #include <iostream> namespace { template<int... args> struct ArrayHolder { static const int data[sizeof...(args)]; }; template<int... args> const int ArrayHolder<args...>::data[sizeof...(args)] = { args... }; template<size_t N, int value, int... args> struct generate_array { typedef typename generate_array<N-1, value, value, args...>::result result; }; template<int value, int... args> struct generate_array<0, value, args...> { typedef ArrayHolder<args...> result; }; } int main() { typedef generate_array<5, 42>::result A; for (auto x : A::data) std::cout << x << '\n'; } 

Example:

 $ g++ -std=c++11 initialize-array.cc && ./a.out 42 42 42 42 42 
     #include <iostream> using namespace std; int main(){ int arr1[] = { 1, 2, 5 }; // массив из целых чисел 1 2 5 int arr11[3] = { 1, 2, 5 }; // то же что и выше int arr2[3][3] = { 1, 2, 3, // двумерный массив 4, 5, 6, // заполненный целыми 7, 8, 9 // числами от 1 до 9 }; return 0; } 

    UPD: Still Found Array Initialization Option

     #include <iostream> #include <valarray> using namespace std; int main(){ valarray<int> v(5); v = 12; // присвоить всем значениям массива число 12 for (int i = 0; i < 5; i++) cout << v[i] << endl; return 0; } 
    • one
      for what a minus? - perfect
    • @perfect what you propose is called Chinese code - manually fill all values. It can still be tolerable for an array of 5-10 elements. And if these elements will be a thousand? Then, by golly, it's better to use a cycle. - DreamChild
    • 2
      @perfect, in my opinion it should just be obvious that the author of the question was not interested in the trivial version proposed by you (in case of doubt, it’s better to clarify what the author really needs by making a comment on the question rather than writing the answer right away). - avp
    • one
      @avp what the question is, is the answer. As far as I understand, not only the author uses questions, but also the people who come, this is the meaning of the questionnaires. But the accepted answer @manking in general in C ++ does not work, although the tag-tag is exactly C ++. - perfect
    • one
      updated answer. Found another way to initialize an array of values ​​with a number at any time - perfect