4
#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]'

linrongbin
  • 2,967
  • 6
  • 31
  • 59
  • 1
    You should use [std::array](http://en.cppreference.com/w/cpp/container/array), raw arrays are finicky and decay to pointers to their first element as soon as you look at them. – Borgleader Jul 06 '16 at 01:20
  • `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 function – M.M Jul 06 '16 at 02:11
  • oh sorry, i made a mistake – linrongbin Jul 06 '16 at 11:38

3 Answers3

13

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • I generate some int array in one function, each array is an int[60] array. I want to return all these arrays when function end. so I think I need a container like vector v, when I generate a new array, I can just push the new int array into vector. – linrongbin Jul 06 '16 at 11:45
  • 2
    Use `std::vector` for the arrays themselves. You obviously know all about `std::vector`. – Sam Varshavchik Jul 06 '16 at 11:48
5

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)

Logman
  • 4,031
  • 1
  • 23
  • 35
3

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]));
shole
  • 4,046
  • 2
  • 29
  • 69
  • sizeof(s) - this can be tricky as you can use int s[] as function parameter and it will be converted to int* s and you will get sizeof(int*) – Logman Jul 06 '16 at 01:30
  • You are right, base on this post : http://stackoverflow.com/questions/4108313/how-do-i-find-the-length-of-an-array I was assuming he is using C style array as he stated at OP – shole Jul 06 '16 at 01:33
  • no, I need collect lots of array with a container, such as vector. each array is a int[60]. – linrongbin Jul 06 '16 at 11:46