3

Possible Duplicate:
Static array initialization of individual elements in C++

In C, I can initialize specific subscript item in array like this:

int array[100] = {[22] = {1}, [33] = {33}};

but this snippet can not compile by g++. so how can I initialize specific subscript item in array by c++.

Community
  • 1
  • 1
Xinyu NG
  • 301
  • 1
  • 2
  • 7

5 Answers5

1

You cannot. This is not legal C++ code.

You'll need to initialize the whole array, and then assign the specific elements later. Perhaps:

int array[100] = {};
array[22] = 1;
array[33] = 33;
John Dibling
  • 99,718
  • 31
  • 186
  • 324
1

The subscript initialization is only allowed in C and not in C++. You can check the detailed documentation here http://publib.boulder.ibm.com/infocenter/compbgpl/v9v111/index.jsp?topic=/com.ibm.xlcpp9.bg.doc/language_ref/aryin.htm

If you want to initialize each element, you can do it after declaring the array and in the following lines initializing the values;

#include<iostream>
using namespace std;

int main(){
    int arr[100];
    arr[22]=33;
    arr[33]=66;
    cout<<arr[22]<<"\t"<<arr[33];
    return 0;
}

It produces the following output:

$ ./a.exe
33      66
Shubhanshu Mishra
  • 6,210
  • 6
  • 21
  • 23
1

Well, I am waiting on SO for goals like yours :D

In C++ we have std::array and std::std::initializer_list - so why not combine these two things together, to make this works:

int main() {
   CArray<int, 7> a { E[1] = 13, E[6] = 14 };
   for (int i = 0; i < 7; ++i) {
      std::cout << a[i] << std::endl;
   } 
}

And produce this output:

0
13
0
0
0
0
14

So, where is magic?

Initialize std::array from std::initializer_list<EIV_t<T>> where:

template <class T>
struct EIV_t {
  size_t i;
  T      v;
};

The new std::array:

template <class T, size_t N>
class CArray : private std::array<T,N> {
  typedef std::array<T,N> Base;
public:
  CArray() : Base() {}
  CArray(std::initializer_list<T> l) : Base(l) {}
  CArray(std::initializer_list<EIV_t<T>> l) : Base() {
     for (auto i = l.begin(); i != l.end(); ++i) {
         (*this)[i->i] = i->v;
     }
  }

  // well, private inheritance has its cost
  using Base::operator [];
  // a lot of missing...
};

The rest of magic:

class EI_t {
public:
  EI_t(size_t i) : i(i) {}
  template <class T>
  EIV_t<T> operator = (const T& v) const
  {
     return EIV_t<T> { i, v };
  }
private:
  size_t i;
}; 
class E_t {
public:
  EI_t operator [] (size_t i) const { return EI_t(i); }
}; 
E_t E;

Full example: http://ideone.com/nzWL0

PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
0

You can't, you can only assign it after the fact.

Scrubbins
  • 150
  • 4
0

You can write :

array[22] = 1;
array[33] = 33;