Click here to Skip to main content
13,193,551 members (50,079 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

45.6K views
227 downloads
5 bookmarked
Posted 27 Jan 2011

Associative Array in C++

, 30 Jan 2011
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

arnavguddu
Student Institute of RadioPhysics & Electronics
India India
I am a Student of Institute of RadioPhysics & Electronics (University of Calcutta), studying Post-B.Sc. B.Tech.(RadioPhysics). As both Electronics and Computer Science/Programming are my hobby, I play around with them all the time.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 1 Pin
lazair2025-Jul-13 23:39
memberlazair2025-Jul-13 23:39 
GeneralMy vote of 5 Pin
Hafiz Bistar18-Jan-13 17:12
memberHafiz Bistar18-Jan-13 17:12 
General[My vote of 1] My vote of 1 Pin
Didier Dobrovitch3-Feb-11 5:38
memberDidier Dobrovitch3-Feb-11 5:38 
GeneralMy vote of 5 Pin
steveb31-Jan-11 5:43
membersteveb31-Jan-11 5:43 
GeneralMy vote of 5 Pin
steveb31-Jan-11 5:38
membersteveb31-Jan-11 5:38 
GeneralMy vote of 2 Pin
snija030-Jan-11 19:45
membersnija030-Jan-11 19:45 
GeneralMy vote of 1 Pin
jean Davy29-Jan-11 21:48
memberjean Davy29-Jan-11 21:48 
GeneralMy vote of 1 Pin
Gordon Brandly28-Jan-11 10:19
memberGordon Brandly28-Jan-11 10:19 
GeneralAlso a vote 1 for all comments Pin
trotwa28-Jan-11 10:15
membertrotwa28-Jan-11 10:15 
GeneralRe: Also a vote 1 for all comments Pin
steveb28-Jan-11 11:20
membersteveb28-Jan-11 11:20 
GeneralMy vote of 1 Pin
brovushkin28-Jan-11 8:24
memberbrovushkin28-Jan-11 8:24 
GeneralMy vote of 2 Pin
JohnAGonzalez28-Jan-11 5:22
memberJohnAGonzalez28-Jan-11 5:22 
GeneralMy vote of 1 Pin
rembo66628-Jan-11 3:33
memberrembo66628-Jan-11 3:33 
GeneralMy vote of 1 Pin
Stephen Hewitt28-Jan-11 2:45
memberStephen Hewitt28-Jan-11 2:45 
GeneralMy vote of 2 Pin
hnwyllmm28-Jan-11 2:09
memberhnwyllmm28-Jan-11 2:09 
GeneralMy vote of 1 Pin
Serge Savostin28-Jan-11 2:08
memberSerge Savostin28-Jan-11 2:08 
GeneralMy vote of 1 Pin
Emilio Garavaglia28-Jan-11 1:36
memberEmilio Garavaglia28-Jan-11 1:36 
General[My vote of 1] well Pin
Tim Sabo28-Jan-11 0:40
memberTim Sabo28-Jan-11 0:40 
GeneralMy vote of 3 Pin
legendlegend51828-Jan-11 0:33
memberlegendlegend51828-Jan-11 0:33 
GeneralMy vote of 1 Pin
Marco Mastropaolo28-Jan-11 0:26
memberMarco Mastropaolo28-Jan-11 0:26 
GeneralMy vote of 1 Pin
Ollie C28-Jan-11 0:17
memberOllie C28-Jan-11 0:17 
General[My vote of 1] std::map ? [modified] Pin
Selvin28-Jan-11 0:12
memberSelvin28-Jan-11 0:12 
GeneralLooks interesting but... Pin
Ashley Davis27-Jan-11 23:50
memberAshley 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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171018.2 | Last Updated 31 Jan 2011
Article Copyright 2011 by arnavguddu
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid