Lalit Verma
Lalit Verma

Reputation: 802

Way to put more than 1 element in an array index

I am looking for any kind of programming data structure that can store multiple values at single position.

For example

Assume a array in which at each index we have multiple values:

For example if array size is 5 then at index 0 we have :1,2,3;
at index 1 we have : 4,5;
at index 2 : 1,8,9,4;
and so on...

Is there any data structure to do this other than linked-list.
Programming language in which i am looking for: JAVA/ C/ C++/ lisp

Upvotes: 0

Views: 863

Answers (1)

Zakir
Zakir

Reputation: 2382

You have to use an array of a dynamic container like a vector or a list. Here's a C++ implementation using Array of vectors:-

using namespace std;    

#include <iostream>
#include <vector>

#define ARRAY_SIZE 5

int main ()
{
    vector<int> array[ARRAY_SIZE];  //An array (5 element) of vectors 

    array[0].push_back(1);
    array[0].push_back(2);
    array[0].push_back(3);

    array[1].push_back(4);
    array[1].push_back(5);

    array[2].push_back(1);
    array[2].push_back(8);
    array[2].push_back(9);
    array[2].push_back(4);

    for(int i=0; i<ARRAY_SIZE; i++)
    {
        cout<<"Contents at array index: "<< i <<":";
        for(vector<int>::iterator it = array[i].begin(); it != array[i].end(); ++it)
        {
            cout << ' ' << *it;
        }
        cout << "\n";
    }           

    return 0;
}

Output:-
Contents at array index: 0: 1 2 3
Contents at array index: 1: 4 5
Contents at array index: 2: 1 8 9 4
Contents at array index: 3:
Contents at array index: 4:

Upvotes: 1

Related Questions