Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between std::vector::empty and std::empty

Tags:

c++

std

To check if a vector v is empty, I can use std::empty(v) or v.empty(). I looked at the signatures on cppreference, but am lacking the knowledge to make sense of them. How do they relate to each other? Does one implementation call the other?

I know that one comes from the containers library and the other from the iterators library, but that is about it.

like image 223
lursyy Avatar asked Sep 13 '25 00:09

lursyy


1 Answers

Difference between std::vector::empty and std::empty

The difference between Container::empty member function and std::empty free function (template) is the same as difference between Container::size,std::size, Container::data,std::data, Container::begin,std::begin and Container::end,std::end.

In all of these cases for any standard container, the free function (such as std::empty) simply calls the corresponding member function. The purpose for the existence of the free function is to provide a uniform interface between containers (and also std::initializer_list) and arrays. Arrays cannot have member functions like the class templates can have, so they have specialised overload for these free functions.

If you are writing code with a templated container type, then you should be using the free function in order to be able to support array as the templated type. If the type isn't templated, then there is no difference between the choice of using member function or the free function other than the convenience of potential refactoring into a template (or just plain array).

like image 89
eerorika Avatar answered Sep 14 '25 15:09

eerorika