Can i push an array of int to a C++ vector?

后端 未结 8 1374
臣服心动
臣服心动 2020-12-15 21:03

Is there any problem with my code ?

std::vector weights;
int weight[2] = {1,2};
weights.push_back(weight);

It can\'t be compi

相关标签:
8条回答
  • 2020-12-15 21:23

    The reason arrays cannot be used in STL containers is because it requires the type to be copy constructible and assignable (also move constructible in c++11). For example, you cannot do the following with arrays:

    int a[10];
    int b[10];
    a = b; // Will not work!
    

    Because arrays do not satisfy the requirements, they cannot be used. However, if you really need to use an array (which probably is not the case), you can add it as a member of a class like so:

    struct A { int weight[2];};
    std::vector<A> v;
    

    However, it probably would be better if you used an std::vector or std::array.

    0 讨论(0)
  • 2020-12-15 21:23

    You should use std::array instead of simple array:

    #include <vector>
    #include <array>
    
    std::vector<std::array<int, 2>> weights;
    std::array<int, 2> weight = {1, 2};
    weights.push_back(weight);
    

    or with a constructor:

    std::vector<std::array<int, 2>> weights;
    weights.push_back(std::array<int, 2> ({1, 2});
    
    0 讨论(0)
提交回复
热议问题