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

后端 未结 8 1373
臣服心动
臣服心动 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:11

    To instantiate the vector, you need to supply a type, but int[2] is not a type, it's a declaration.

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

    Arrays aren't copy constructable so you can't store them in containers (vector in this case). You can store a nested vector or in C++11 a std::array.

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

    Just use

    vector<int*>  .That will definitely work.
    

    A relevant discussion on the same topic : Pushing an array into a vector

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

    You cant do that simply.

    It's better you use either of these:

    1. vector <vector<int>> (it's basically a two dimensional vector.It should work in your case)

    2. vector< string > (string is an array of characters ,so you require a type cast later.It can be easily.).

    3. you can declare an structure (say S) having array of int type within it i.e.

      struct S{int a[num]} ,then declare vector of vector< S>

    So indirectly, you are pushing array into a vector.

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

    Array can be added to container like this too.

        int arr[] = {16,2,77,29};
        std::vector<int> myvec (arr, arr + sizeof(arr) / sizeof(int) );
    

    Hope this helps someone.

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

    One possible solution is:

        std::vector<int*> weights;
        int* weight = new int[2];
        weight[0] =1; weight[1] =2;
        weights.push_back(weight);
    
    0 讨论(0)
提交回复
热议问题