Using std::map

using TMap=std::map; why it’s a wrong declaration?


and why such declaration is complicated?

My stab at the answer: because #define is used for identifiers, which std::map is, vs. types, of which int is…

No… as the lecture was told we can use using TMap instead of #define, but define is better in this case

Ah - likely due to needing an argument list for the class std::map, which can’t be provided at this level… Thus the #define being a better option.

on the contrary #define int32 int; also is a wrong declaration
in the end what is different between #define and using

#define” is used for token substitutions (such as constants, variable names, etc.), whereas “using” is for namespace declarations & type aliasing.

“std::map” is a variable name - which is a token; int is a type and thus needs type aliasing.

Fine lines, but there you go.

1 Like

and do you know what is different between map and pair?
it has the same syntax pair<char,bool>

std::pair is a struct template that provides a way to store two heterogeneous objects as a single unit.

std::map is a sorted associative container that contains key-value pairs with unique keys.

(quotes taken from documentation)

First answer here answers your question. In short, map is a little more robust, however, if needs are simple, may be overkill.

C++ code passes through certain stages to become a binary (.e.g EXE on Windows).

preprocessor > compiler > linker > EXE

Now #define is a preprocessor directive which is a direct token substitution before the compiler begins
So your code
#define TMap std::map
is always working as the compiler won’t see TMap at all (would be substituted during pre-processing)

On the other hand, using = is a compile-time alias declaration and you have to play with the compiler rules, and as std::map is not a complete type (unlike e.g. std::string) but a name of a template (a not so easy topic in C++), you have to specify if the using = is a complete type or a template in itself. E.g. the correct way of doing using = in this case would be this:

// This works
using TMap = std::map<char, bool>;

// This will work too. (aliasing the whole template):
template<class K, class V>
using TMap = std::map<K, V>;
1 Like

thank you :slight_smile:

Privacy & Terms