Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

C++ string lookup table?

Posted on 2014-01-23
3
Medium Priority
?
1,414 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 1000 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 35

Accepted Solution

by:
sarabande earned 1000 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
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 goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…

722 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