简体   繁体   中英

Insert array pointer to a 2 dimension vector in C++

I want to ask in C++, how to insert an array to the end of a 2 dim array?
my code,which still will get error from compiler , is like this

int *A;
A = new int[10];
vector<vector<int>> myarray;

for (int j = 0; j < 5; j++)
{
    for (int i = 0; i < 10; i++)
    {
        A[i] = i + j;

    }

    myarray.push_back(vector<int>{10});

    copy(A, A + 10, myarray.back());
    }

the error is

C2794: 'iterator_category' : is not a member of any direct or indirect base class of 'std::iterator_traits<_OutIt>'

Easyiest way is not to push an array to the back, but an vector. The following code works, because the call to vector::push_back, makes a copy of a and pushes it back myarray.

vector<int> A(10);
vector<vector<int>> myarray;

for (int j = 0; j < 5; j++)
{
    for (int i = 0; i < 10; i++)
    {
        A[i] = i + j;
    }
    myarray.push_back(A); // push one line for each j=0 to 4 to the back of my array
}

The problem here is that you're really not putting the vector A into the vector, myArray. What you're doing is putting an vector that only contains 10, into myArray, since you're doing this....

myarray.push_back(vector<int>{10});

What you want to do is populate vector A, which you have already done, and then..

myarray.push_back(A);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM