Question about storing array in a std::vector in C++

前端 未结 7 1289
灰色年华
灰色年华 2021-01-12 17:07

I am unclear about the following.

First, this code compiles fine:

#include 

typedef struct{
    int x1,x2,x3,x4;
}  ints;

typedef std         


        
7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 17:22

    error: ISO C++ forbids initialization in array new
    error: array must be initialized with a brace-enclosed initializer
    error: invalid array assignment
    error: request for member ‘~int [4]’ in ‘* __p’, which is of non-class type ‘int [4]’

    To understand one of the errors, imagine the following:

    void main() {
        int a[4] = {0,1,2,3};
        int b[4] = a;
    }
    

    As opposed to:

    typedef struct{
        int x1,x2,x3,x4;
    }  ints;
    
    int main()
    {
        ints a;
        ints b = a;
    }
    

    Or even:

    typedef struct{
        int x[4];
    }  ints;
    
    int main()
    {
        ints a;
        ints b = a;
    }
    

    C/C++ arrays cannot be copied via the assignment operator, though structs containing arrays can be.
    So an easy fix is to do:

    typedef struct{
            int x[4];
    }  ints;
    
    typedef std::vector vec;
    
    int main(){
            vec v;
            ints a = { {0,1,2,3} };
            v.push_back(a);
    }
    

提交回复
热议问题