Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to push_back an array int[10] to std::vector<int[10]>?

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

like image 512
linrongbin Avatar asked Nov 29 '22 09:11

linrongbin


2 Answers

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.

like image 81
Sam Varshavchik Avatar answered Dec 05 '22 08:12

Sam Varshavchik


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)

like image 42
Logman Avatar answered Dec 05 '22 06:12

Logman