Alexandru
Alexandru

Reputation: 12902

How do you get the number of elements in a std::map as an unsigned long?

How do you get the number of elements in a std::map as an unsigned long?

Assuming you have an object like this:

std::map<unsigned long, someClass *> myNightmare;

I have been trying to figure out how to get its number of elements. You see, I need this number as an unsigned long, and it doesn't seem correct to just do this:

unsigned long count = myNightmare.size();

So how should you get the number of elements as an unsigned long?

Upvotes: 3

Views: 6565

Answers (2)

Shoe
Shoe

Reputation: 76240

To be really portable and correct you should use the standard std::size_t or more precisely std::map<unsigned long, someClass*>::size_type.

The latter is the type returned from std::map::size, but it does not, generally, differ from the more generic std::size_t.

If you really want to still use long unsigned, then your line:

unsigned long count = myNightmare.size();

will perform an implicit conversion for you, already.

Upvotes: 2

poljpocket
poljpocket

Reputation: 318

Use static cast.

long unsigned mySize = static_cast<long unsigned>(myNightmare.size());

Upvotes: 7

Related Questions