0

I'm very new to C++. I just started to pick it up this last week or so.

I am trying to write a macro to be able to access and add items to a std::map. However, I'm not finding this to work. What am I doing wrong or is there a better way to implement this?

#include <iostream>
#include <string>
#include <map>

typedef struct {
  std::string name;
  int value;
} Token;

std::map<std::string, Token> ALL_TOKENS;

#define T(macro, name, value) \
  Token macro {name, value}; \
  ADD(name, macro); \
  T(TEST, "Test", 1); \

#define ADD(str, tok) \
  ALL_TOKENS.insert(std::pair<std::string, Token>(str, tok)); \

#define GET(str) \
  ALL_TOKENS[str]; \

int main(int argc, const char * argv[]) {
  Token tok = GET("Test");
  printf("%s", tok.name.c_str());
  return 0;
}
4
  • 2
    Is there a better way? I can hardly think of a worse way... Commented Nov 16, 2014 at 2:21
  • @KerrekSB Ok...? I'm new to c++. I just picked it up last week. Commented Nov 16, 2014 at 2:23
  • Forget about macros and focus on classes Commented Nov 16, 2014 at 2:29
  • 1
    Looks like you created more work with the macros than you are benefiting from. Commented Nov 16, 2014 at 2:51

2 Answers 2

2

In my opinion, your macros make the code more difficult to understand. It also looks to me like you don't entirely understand std::map yet.

When I use map, I usually use operator[] for insertion, and possibly for retrieving as well. It's usually easiest if you think of it just as an array that can use essentially any (sortable) type as a subscript.

For example, to count how often each word occurs in a file, you could do something like this:

std::string word;
std::map<std::string, size_t> counts;

while (infile >> word)
    ++counts[word];

Then you could print out all the words and how often each was found (in alphabetical order) with code something like this:

for (auto const &w : counts)
    std::cout << w.first << "\t" << w.second << "\n";

At least to me, this seems simpler and more understandable than any code I could write using your macros.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you're response helped the most.
0

Disregarding the poor choice of using macros to access functionality...

You are not getting any output since you have not added anything to the map.

Try

int main(int argc, const char * argv[]) {
  Token t{"Test", 10};
  ADD("Test", t);
  Token tok = GET("Test");
  printf("%s\n", tok.name.c_str());
  return 0;
}

You'll get some output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.