감동, 마음이 움직이는 것

[c++] vector of vector 본문

Tips (Utility, Computer Language, and etc.)

[c++] vector of vector

Struggler J. 2018. 8. 23. 01:51

I wanted to make a vector of integer arrays. 

However, I treated int*, when I attempt to push_back the int* into a vector, just address is copied (shallow copy). 

I want to do deep copy.

So, I tried to search the solution, and I found the vector of vectors as a solution. 


Following is a simple example:

=================================== code ==================================

#include <iostream>

#include <vector>


vector< vector<int> > vec;

vector<int> arr;

int Ns = 10;

int* x = (int*)calloc(Ns, sizeof(int));


//main calculation
for(int i=0; i<maxt; i++) {
//your model dynamics which gives the results in x array
run(x);

//deep copy x array to arr vector
arr.erase( arr.begin(), arr.end() );
arr.insert( arr.begin(), x, x+Ns );

//push_back to vec
vec.push_back(arr);
}

//printing the vector of vector 

for(int i=0; i<vec.size(); i++) {

for(int l=0; l<vec[i].size(); l++) {

cout << vec[i][l] << " ";

}

cout << endl;

}

=========================================================================


Important functions:

.size()                                    : gives the size of vector

.push_back(elem)                  : add elem to the vector at the end

.erase(start, end)                   :  erase elements from start to end, two arguments are addresses.

.insert(position, start, end)    : insert the data from start to end at position, all arguments are addresses.

.begin()                                  : return the starting address of the vector

.end()                                     : return the end point of the address of the vector