allocating vectors (or vectors of vectors) dynamically

Viewed 107111

I need to dynamically allocate 1-D and 2-D arrays whose sizes are given at run-time.

I managed to "discover" std::vector and I think it fits my purposes, but I would like to ask whether what I've written is correct and/or can be improved.

This is what I'm doing:

#include <vector>

typedef std::vector< std::vector<double> > matrix;

//... various code and other stuff

std::vector<double> *name = new std::vector<double> (size);
matrix *name2 = new matrix(sizeX, std::vector<double>(sizeY));
9 Answers

Sometimes you don't want to fill your stack and your memory requirement is large. Hence you may want to use vector> created dynamically especially while creating a table of a given row and col values.

Here is my take on this in C++11

int main() {
    int row, col;
    std::cin >> row >> col;
    auto *arr = new std::vector<std::vector<int>*>(row);
    for (int i=0; i<row; i++) {
        auto *x = new std::vector<int>(col, 5);
        (*arr)[i] = x;
    }

    for (int i=0; i<row; i++) {
        for(int j=0; j<col; j++) {
            std::cout << arr->at(i)->at(j) << " ";
        }
        std::cout << std::endl;
    }
    return 0;
}
 #include < iostream > 
 #include < vector >

 using namespace std;

int main(){

vector<int>*v = new vector<int>();   // for 1d vector just copy paste  it

v->push_back(5);
v->push_back(10);
v->push_back(20);
v->push_back(25);

for(int i=0;i<v->size();i++){
    cout<<v->at(i)<<" ";
}
cout<<endl;

delete v;

system("pause");
return 0;

     }
Related