4
votes
#include <vector>
using namespace std;

vector<int[60]> v;
int s[60];
v.push_back(s);

This code in Visual Studio 2015 community report a compile error:

Error (active) no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=int [60], _Alloc=std::allocator]" matches the argument list

Error C2664 'void std::vector>::push_back(const int (&)[60])': cannot convert argument 1 from 'int' to 'int (&&)[60]'

3
You should use std::array, raw arrays are finicky and decay to pointers to their first element as soon as you look at them.Borgleader
int[10] s; is a syntax error you should get a problem on that line too. Also v.push_back(s) must occur inside a functionM.M
oh sorry, i made a mistakelinrongbin

3 Answers

13
votes

Use std::array, instead:

#include <vector>
#include <array>

using namespace std;

int main()
{
    vector<array<int, 10>> v;
    array<int, 10> s;
    v.push_back(s);
    return 0;
}

But I also have to question the purpose of having a vector containing an array. Whatever is the underlying reason for that, there's likely to be a better way of accomplishing the same goals.

5
votes

You can do it like this:

#include <iostream>
#include <vector>

int main()
{
    int t[10] = {1,2,3,4,5,6,7,8,9,10};

    std::vector<int*> v;

    v.push_back(t);

    std::cout << v[0][4] << std::endl;

   return 0;
}

To be more specific in this solution you do not actually store values of array t into vector v you just store pointer to array (and to be even more specific to first element of array)

3
votes

I am not sure are you saying initialize a vector from an array, if yes here is a way to do it using vector's constructor:

int s[] = {1,2,3,4};
vector<int> v (s,  s + sizeof(s)/sizeof(s[0]));