Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C++

Associative Array in C++

Rate me:
Please Sign up or sign in to vote.
1.21/5 (19 votes)
30 Jan 2011CPOL2 min read 70.9K   264   6   23
Associative Array have been a part of languages like PHP, C#, etc., and now here is how it can be implemented as a feature in C++

Introduction

Associative array had already been a part of some programming language like PHP, C#, etc. It is very useful and unique compared to an indexed based array. But this feature is not available in C++. So, I decided  to add this new feature to the C++ language as well.

Background 

In general, an array represents a collection of elements accessed by a index number. This index base starts at 0 and upwards. But, the only disadvantage that lies with this indexed based array is that, they does not provide for any unique naming for the elements. This disavantage is removed by the introduction of the associative array. An associative array is accessed by using the individual String name corresponding to the element. It is declared as:

assoc_array["element_name"] = 25;   //Element value


Thus, it is simple to declare and use the associative array. And, thus with the help of the following C++ code, the reader may also implement this feature in C++.

/*
 * Program to demostrate the use of template class and associative array.
 * By Arnav Mukhopadhyay
 */

 #include <iostream>
 #include <vector>
 using namespace std;

 template <class T>
 class AssocArray
 {
     private:
         typedef struct _Data
         {
             T data;
             string name;
         } Data ;
         vector<Data> stack;
     public:
         long Size()
         {
             return stack.size();
         }

         bool IsItem(string name)
         {
             for(int i=0; i<Size(); i++)
             {
                 if(stack[i].name == name)
                     return true;
             }
             return false;
         }

         bool AddItem(string name, T data)
         {
             if(IsItem(name))
                 return false;
             Data d;
             d.name = name;
             d.data = data;
             stack.push_back(d);
             return true;
         }

         T& operator [] (string name)
         {
             for(int i=0; i<Size(); i++)
             {
                 if(stack[i].name == name)
                     return stack[i].data;
             }
             long idx = Size();
             Data d;
             d.name = name;
             stack.push_back(d);
             return stack[idx].data;
         }

         string GetItemName(long index)
         {
             if(index<0)
                 index = 0;
             for(int i=0; i<Size(); i++)
                 if(i == index)
                     return stack[i].name;
             return "";
         }

         T& operator [] (long index)
         {
             if(index < 0)
                 index = 0;
             for(int i=0; i<Size(); i++)
             {
                 if(i == index)
                     return stack[i].data;
             }
             return stack[0].data;
         }

   };
 

Using the code

Well, the class declared above is pretty simple. It is a template class, and so can be used to represent an array of any data type. Also it is clear, from the overloading operators that the class, if representing any array, will allow indexed based array access, along with associative array based access, alongwith. The member AddItem(...) can be used to add a array item to the list.

Now on how to use the array. Say we write a piece of code to use the array class with the integer data types. Here is how we do it:-

//  Declare the class to be used with int data type
AssocArray<int>   arr;

// Now add an element to the array using function
arr.AddItem("firstElement", 100);

// Now add an element using [] operator
arr["secondElement"] = 25;

// Now add another element
arr["otherElement"] = 56;

// Here is how to access the element "firstElement" for any other purpose
cout<<"firstElement = " << arr["firstElement"] << endl;

// Here is how to access using index
cout<<"Element 1= " << arr[1] << endl;


// Other functions
// arr.IsItem("some element name") will return true if that item is on the array list or else false
// arr.GetItemName(2) will return the name of the element corresponding to index 2
// arr.Size()   will return the number of items saved on the list

 

History 

Well, Associative array had been implemented for C++ language in here. Although, STL classes are there to simplify and efficiently implement associative array, but it was my own idea to reinvent the wheel and build things grounds up, except for using the vector class. But there are still many features to add up, one of which is LINQ in Visual C#, which is very interesting. My own personal interest lies with bringing LINQ analogy to C++, which is still a work in progress. Till then, this one will be of some good use and my latest addition to Code Project. And thank you all for reading this. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student Institute of RadioPhysics & Electronics
India India
......

Comments and Discussions

 
GeneralMy vote of 1 Pin
lazair25-Jul-13 23:39
lazair25-Jul-13 23:39 
GeneralMy vote of 5 Pin
Hafiz Bistar18-Jan-13 17:12
Hafiz Bistar18-Jan-13 17:12 
General[My vote of 1] My vote of 1 Pin
Didier Do3-Feb-11 5:38
Didier Do3-Feb-11 5:38 
GeneralMy vote of 5 Pin
steveb31-Jan-11 5:43
mvesteveb31-Jan-11 5:43 
As far as application of an article would be poor, the realisation of nessesitty of associative container is well deserveed Big Grin | :-D
GeneralMy vote of 5 Pin
steveb31-Jan-11 5:38
mvesteveb31-Jan-11 5:38 
GeneralMy vote of 2 Pin
snija030-Jan-11 19:45
snija030-Jan-11 19:45 
GeneralMy vote of 1 Pin
jean Davy29-Jan-11 21:48
jean Davy29-Jan-11 21:48 
GeneralMy vote of 1 Pin
Gordon Brandly28-Jan-11 10:19
Gordon Brandly28-Jan-11 10:19 
GeneralAlso a vote 1 for all comments Pin
trotwa28-Jan-11 10:15
trotwa28-Jan-11 10:15 
GeneralRe: Also a vote 1 for all comments Pin
steveb28-Jan-11 11:20
mvesteveb28-Jan-11 11:20 
GeneralMy vote of 1 Pin
brovushkin28-Jan-11 8:24
brovushkin28-Jan-11 8:24 
GeneralMy vote of 2 Pin
John A. Gonzalez (FL)28-Jan-11 5:22
professionalJohn A. Gonzalez (FL)28-Jan-11 5:22 
GeneralMy vote of 1 Pin
Aleksey Vitebskiy28-Jan-11 3:33
Aleksey Vitebskiy28-Jan-11 3:33 
GeneralMy vote of 1 Pin
Stephen Hewitt28-Jan-11 2:45
Stephen Hewitt28-Jan-11 2:45 
GeneralMy vote of 2 Pin
hnwyllmm28-Jan-11 2:09
hnwyllmm28-Jan-11 2:09 
GeneralMy vote of 1 Pin
Serge Savostin28-Jan-11 2:08
Serge Savostin28-Jan-11 2:08 
GeneralMy vote of 1 Pin
Emilio Garavaglia28-Jan-11 1:36
Emilio Garavaglia28-Jan-11 1:36 
General[My vote of 1] well Pin
Tili_us28-Jan-11 0:40
Tili_us28-Jan-11 0:40 
GeneralMy vote of 3 Pin
legendlegend51828-Jan-11 0:33
legendlegend51828-Jan-11 0:33 
GeneralMy vote of 1 Pin
Marco Mastropaolo28-Jan-11 0:26
Marco Mastropaolo28-Jan-11 0:26 
GeneralMy vote of 1 Pin
Ollie C28-Jan-11 0:17
Ollie C28-Jan-11 0:17 
General[My vote of 1] std::map ? [modified] Pin
Selvin28-Jan-11 0:12
Selvin28-Jan-11 0:12 
GeneralLooks interesting but... Pin
Ashley Davis27-Jan-11 23:50
Ashley Davis27-Jan-11 23:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.