Jun 27, 2013 at 2:39am Jun 27, 2013 at 2:39am UTC
I have a 2d array and I created it with pointers.
int **array;
array = new int* [size];
for (int i = 0; i < size; i++)
array[i] = new int [K];
for (int i = 0; i < size; i++){
delete [] array[i];
}
delete [] array;
}
But what I want is to store values in my 2D array that has rows with different number of elements. That is,
1 0 0 1
1 0 1
2 1
1 3 4
and so on. It should probably be dynamic so I should be able to add more rows whenever I want.
Thanks-
Jun 27, 2013 at 2:54am Jun 27, 2013 at 2:54am UTC
I don't understand the case with K. K will be fixed, such as K=5. How can it be 4, 3, 2, and 3? Also, is adding process possible with arrays and pointers?
Jun 27, 2013 at 2:58am Jun 27, 2013 at 2:58am UTC
if K is always 5 then all your row arrays have the same lengths. If you want them to have different lengths, then K would need to change. At what point in your program do you learn that the first row needs to have the length 4? That's the point where you can set K to 4 and create that row.
Jun 27, 2013 at 3:02am Jun 27, 2013 at 3:02am UTC
Okay, it makes sense. it shouldn't be fixed. Then, how can I change that K values for each row? Do I need to add some more lines to my code?
Jun 27, 2013 at 3:36am Jun 27, 2013 at 3:36am UTC
To add new rows, can following set of lines be added before deleting the array?
int* addedRow;
addedRow = new int [size];
Jun 28, 2013 at 9:31pm Jun 28, 2013 at 9:31pm UTC
Hi again!
For the "std::vector" code:
#include <iostream>
#include <vector>
int main()
{
std::vector< std::vector<int> > array =
{{1, 0, 0, 1},
{1, 0, 1},
{2, 1},
{1, 3, 4}};
// can add rows whenever
std::vector<int> row = {1,2,3,4,5};
array.push_back(row);
// can resize existing rows, too
array[0].resize(6);
// print:
for(auto& row: array) {
for(int n: row)
std::cout << n << ' ';
std::cout << '\n';
}
}
I receive some error messages: array must be initialized by constructor, not by {...}. and some more... How can they be fixed?
Last edited on Jun 28, 2013 at 9:42pm Jun 28, 2013 at 9:42pm UTC