Initializer list for dynamic arrays?

后端 未结 5 1619
一个人的身影
一个人的身影 2020-11-30 14:44

It is possible to give an initializer list to the definition of a static array. Example:

int main()
{
  int int_static[2] = {1,2};
}

Is a s

5条回答
  •  一整个雨季
    2020-11-30 15:35

    Given that you're real class is more complex than an int, and constructed from differing values, it's complicated. A vector can be constructed with iterators if you have an existing array/vector with the correct values to default from, or you have to use placement new.

    //vector
    int main()
    {
      int int_static[2] = {1,2};
      std::vector int_dynamic(int_static, int_static+2);
      //this is what everyone else is saying.  For good reason.
    }
    //placement new
    int function_that_returns_constructed_from_values() {
        return rand();
    }
    int main() 
    {
        int count = 2;
        char *char_dynamic = new char[count * sizeof(int)];
        int *int_dynamic = char_dynamic;
        for(int i=0; i~int(); //obviously not really int
        delete []char_dynamic;
    }
    

    Obviously, the vector is the preferred way to do this.

提交回复
热议问题