Solved

C++ string lookup table?

Posted on 2014-01-23
3
953 Views
Last Modified: 2014-01-30
I need a string lookup table, which stores static strings (they won't be changing, so I'd like to disallow that.)

I was thinking of std::map, but I don't know how to make that static. Also, the only way I know to initialize const members in a class is in an initialization list on the constructor, and I don't think I should be initializing a huge table that way.

I also need a composite key, such as:

1. string I want
2. language I want it in
3. units I want it in (metric or US)

I was thinking I could just smoosh that all together into one key, either by concatenating strings (if I use a string key) or adding enumerated numbers (if I make the numbers so they always add up to a unique value).

For the fetching algorithm I may add some logic, such as if there's no match, then see if there's an entry for no units (units don't matter) or no language (answer is the same regardless of language).

Still I don't know how to make std::map a readonly table and initialize it.
0
Comment
Question by:deleyd
  • 2
3 Comments
 
LVL 2

Expert Comment

by:alcindor
ID: 39805239
Please see attached file that gives an idea of what I think you are interested in.
A class is coded for your table. A test function tests the class by searching for a given string, language and unit and returns the required string.
You don't need to make the map read only, If you want to access your table like you would a map the you can code an [] operator function in the MyLookuptable class as follows

    string operator[](string key);
    {
        string s="";
        if(m.count(key)>0)
            s = m[key]
        return s;
    };

you could then make a key for the string that you want and access the string as follows

result = (*t)[key];  // result will be an empty string if not found
0
 
LVL 2

Assisted Solution

by:alcindor
alcindor earned 250 total points
ID: 39805243
File didn't upload so here it is:
#include <map.h>

class MyLookupTable
{
    private:
    map<string,string>m;
    void LoadTableFromfile(char *datafilename);
    public:
    MyLookupTable(char *datafilename);
    ~MyLookupTable();
    string MakeKey(string str,string language,string units);
    bool FindString(string key,string &result);
};


//////////////////////////////////////////////////////
MyLookupTable::MyLookupTable(char *datafilename)
{
    LoadTableFromfile(datafilename);
}
MyLookupTable::~MyLookupTable()
{
}

string MyLookupTable::MakeKey(string str,string language,string units)
{ // concatenate the string,language an units, delimiting with a colon :
    string k;

    k = str + ":" + language + ":" + untits;
    return k
}

void MyLookupTable::LoadTableFromfile(char *datafilename)
{   // initialise the map with data from a file for example
    // open a file and read in each string,language and unit
    // use the MakeKey function to produce a key
    // add the string to the map usig the key just obtained

    m[key] = string;
    return;
}

bool MyLookupTable::FindString(string str,string language,string units,string &result)
{   // function returns the value from the map in the callers parameter
    // returns true if found or false otherwise
    string key;
    bool rtn = false

    result = "";
    key = MakeKey(str,language,units);
    if(m.count(key)>0)
    {   // string has been found
        result = m[key];
        rtn = true;
    }
    return rtn;
}
///////////////////////////////////////////////////////////
Testingfunction()
{
    string result,s,key,lang,unit;

    MyLookupTable *t = new MyLookupTable("Initialisationfile.txt");

    s = "Hello";
    lang = "French";
    unit = "1";
    key = t->MakeKey(s,lang,unit);
    if(t->FindString(key,result))
    { // process result with language and unit

    }
    else
    {
        lang = "";
        key = t->MakeKey(s,lang,unit);
        if(t->FindString(key,result))
        { // string found with unit but not language

        }
        else
        {
            unit = "1";
            lang = "";
            if(t->FindString(key,result))
            {   // string found with language but not unit

            }
            else
            {
                unit = "";
                if(t->FindString(key,result))
                {   // string found without unit or language

                }
                else
                {
                    //string not found at all
                }
            }
        }
    }
}
0
 
LVL 32

Accepted Solution

by:
sarabande earned 250 total points
ID: 39805905
a lookup table for strings can be made by a std::set<std::string> rather than a std::map. the latter is sensible if you have data for each string and the string is the key to the data.

you cannot initialize the std::set (or std::map) directly, but you can do a trick:

you cannot add at position i if the vector has not already i elements.

so for an empty vector the statement

i.insert(i.begin()+offset,myvalue);

Open in new window

would throw an exception if offset is greater 0.

note, the iterator end() always is a pseudo iterator only when the vector is empty and no internal array exists. in all other cases it points to a real address one slot behind the last element.

because of that you also could use pointers to a  c array when a function requires iterators:

static const std::string arr[MAX_KEYS]  = { "ABC", "DEF", "GHI", "JKL" , ...};
std::set<std::string> myset(&arr[0], &arr[MAX_KEYS]);

      ... 

Open in new window


this would put the static array to the set and you could make a lookup by

if (myset.find("XYZ") !=myset.end())
{
       // key found

Open in new window


alternatively you could do:

if (std::find(&arr[0], &arr[MAX_KEYS], "XYZ") != &arr[MAX_KEYS])
{
       // key found

Open in new window


and spare the std::set. if you have less than a few hundred keys, the differences for the average lookup are not measurable.

if you want the std::set but don't want to have a static array permanently loaded in memory you could put the filling of the std::set into a function and and make the array non-static.

Sara
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now