Home > Net >  Why std::map::erase returns int rather than bool?
Why std::map::erase returns int rather than bool?

Time:10-10

I wonder why std::map::erase has an overload that returns an int that represents the number of elements erased; so as long as the elements are unique so the number is either 1 or 0. In this case why it doesn't return bool rather than an int?

     std::map<std::string, std::size_t> containers{
    {"map", 1}, {"set", 10}, {"map", 5}, {"vector", 4}, {"array", 7}
};

for(auto const& p : containers)
    std::cout << p.first << " " << p.second << '\n';

std::cout << containers.erase("map") << '\n'; // 1
std::cout << containers.erase("map") << '\n'; // 0

for(auto const& p : containers)
    std::cout << p.first << " " << p.second << '\n';

CodePudding user response:

The answer to your question becomes obvious once you consider what std::multimap::erase returns.

That container's erase() method might return 0, it might return 1, or it might return some other value.

Having a consistent interface that's consistent across containers allows for implementation of templates and algorithms that work equally well with either container, since the return value from erase(), whether it's a map or a multimap, means exactly the same thing.

P.S. Without looking it up, you should be able to make a pretty good guess what std::set's and std::multiset's erase() methods return.

CodePudding user response:

All the c ordered associative containers are based off of a binary search tree, are related, and this is reflected in their similar interfaces.

  • Related