Dictionary

Dictionary is a container that holds a list of unique key-value pairs. This section describes how to create, access, and modify dictionaries, along with examples.

Creating Dictionaries

Use the function createDictionary defined in the header <Util.h>. The following is the syntax to declare a dictionary:

static Dictionary* createDictionary(DATA_TYPE keyType, DATA_TYPE valueType);

Arguments

  • keyType: The data type for the keys of the created dictionary, such as DT_INT, DT_DATE, etc.
  • valueType: The data type for the values of the created dictionary, such as DT_INT, DT_DATE, etc.

Examples

    DictionarySP dic = Util::createDictionary(DT_INT, DT_STRING);  //create a dictionary with keys of INT type and values of STRING type

Operations on Dictionaries

Listed below are some commonly utilized functions for operations on dictionaries:

bool set(const ConstantSP& key, const ConstantSP& value)                      //Add a key-value pair. If the 'key' already exists, update its value.
bool remove(const ConstantSP& key);                                           //remove 'key' and its value from a dictionary
void contain(const ConstantSP& target, const ConstantSP& resultSP) const;     //determine if a dictionary contains the 'target'
ConstantSP getMember(const ConstantSP& key) const;                            //get the value of the specified 'key'
INDEX size() const;                                                           //get the number of key-value pairs in a dictionary
void clear();                                                                 //clear all keys

Examples

dic->set(new Int(1), new String("123"));                                      //1 -> "123"
dic->set(new Int(2), new String("456"));                                      //1 -> "123", 2 -> "456"
dic->remove(new Int(2));                                                      //1 -> "123"
dic->set(new Int(1), new String("777"));                                       //1 -> "777"

ConstantSP result = new Bool;
dic->contain(new Int(3), result);                                             //result : false
dic->contain(new Int(1), result);                                             //result : true
ConstantSP value = dic->getMember(new Int(1));
std::cout << dic->size() << std::endl;                                        //1
dic->clear();
std::cout << dic->size() << std::endl;                                        //0