best practice - where and how to declare constant multi-hash

I'm a relative c/c++ newbie and this is 'the best practice' question.

I need to define a number of job categories (arts, education, engineering,
leisure and sports, marketing, ...) and for each category corresponding sub-categories (eg. for engineering we could have civil, electrical, mechanical, ...).

I'm using QT and was thinking of QMultiHash which allows me to specify multiple values for each key. These keys/values won't change, but I need to list them all (probably 20-30 categories with 10-30 subcategories each).

My question is where (should that be in *.h or *.cpp) and how to define them? Would you use multi-hash as well? What's the best c++ practice for that?

Thanks
I'm not familiar with the QT constructs available. But the C++ STL provides containers sufficient for this task.

Personally, I'd use a map of strings and a vector of strings. This allows you to do exactly as you have asked.

In standard OO the declaration for the container would occur within the declaration for your class (.h). But this depends on if you are using OOD or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <map>
#include <vector>

using namespace std;

int main() {

  map<string, vector<string> > list;

  list["cat1"].push_back("sub_cat1");
  list["cat1"].push_back("sub_cat2");
  list["cat2"].push_back("sub_cat3");
  list["cat2"].push_back("sub_cat4");

  map<string, vector<string> >::iterator mapPtr;
  vector<string>::iterator vectorPtr;

  mapPtr = list.begin();
  while (mapPtr != list.end()) {
    cout << "Current Category: " << (*mapPtr).first << endl;

    vectorPtr = (*mapPtr).second.begin();
    while (vectorPtr != (*mapPtr).second.end()) {
      cout << " - " << (*vectorPtr) << endl;
      vectorPtr++;
    }

    mapPtr++;
  }

  return 0;
}
Thanks for your response. QT constructs are quite similar to what you've provided. However, although I have it working my question is still open - what's the best place to put these in?

This is where my inexperience with C/C++ comes out. I'm OK-ish with c++ syntax, debugging, etc (search on the Internet is usually sufficient). Also, many tutorials/books are very useful. However, finding 'best practice' tips is not as easy.

So, shall I create a separate class for my category/subcategory table, or should I put it in main.cpp, or define that in a header file? What is the best practice?
std::multi_map is what you want.

I'd probably use enums in which case the declaration of the enum should go in a header file.

Or if you need to print out the category names then you might consider

extern const std::string Mechanical;
...

in the header file and put their actual instantiations in a .cpp file.

Last edited on
Excellent - thanks for that. That's what I wanted to know.
Topic archived. No new replies allowed.