HOW CAN I CREATE A RAGGED DYNAMIC ARRAY

Hi everyone, I have a school project to create a dynamic ragged array. below is my incomplete code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;

typedef *int IntPtr;

int main()
{
   IntPtr *p
   p[1] = new int[6]
   p[2] = new int[7]
   p[3] = new int[8]
   p[4] = new int[3] 
    .
    .
    .

my problem here is that, since the inner arrays are not even, it seems like i need a for-loop for every element of p but i do not believe that that is an ideal solution to my problem because, what if p had 100 elements? does that mean i need 100 for-loops? I don't think so. If anyone has a better idea to solve this problem i would really appreciate it. thanking you in advance
You can create an array, in which you store the size of each inner array, and then use its elements as the upper-limit for your loop.

I would like to point out that arrays in C and C++ start from 0, not from 1 as your code is.
Last edited on
1
2
3
4
5
6
7
8
9
#include <vector>

int main()
{
    // http://www.cprogramming.com/tutorial/stl/vector.html
    std::vector< std::vector<int> > ragged(100) ;
    for( std::size_t i = 0 ; i < ragged.size() ; ++i )
        ragged[i] = std::vector<int>( i%10 + 5,  i ) ;
}
@TheDestroyer, Your idea is good, but what i don't like about it is that I have to manually specify the size for each inner array, which takes me back to the question of "What if i've got 100 inner arrays".

@JLBorges, what does the following statement do. vector<int>( i%10 + 5, i ) ; and is it possible to make this a dynamic vector?
> what does the following statement do. vector<int>( i%10 + 5, i ) ;

Oh! That was just for illustration - it creartes a vector containing i%10 + 5 int values, each one of those ints initialized with i.

> and is it possible to make this a dynamic vector?

A vector<> is dynamically resizeable.
See: http://www.cplusplus.com/reference/stl/vector/
Topic archived. No new replies allowed.