Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What type of value should it be returned by getters that return size of vector?

Tags:

c++

What type of value should be returned by getters that return size of vector?

For example I have many getters in my project of the following type and I need the (int) cast to remove the compile warnings:

int getNumberOfBuildings() const { return (int)buildings.size(); }
like image 912
user2381422 Avatar asked Jul 06 '13 20:07

user2381422


2 Answers

The C++03 way:

std::vector<Building>::size_type getNumberOfBuildings() const
{ return buildings.size(); }

The C++11 way:

auto getNumberOfBuildings() const -> decltype(buildings.size())
{ return buildings.size(); }

The C++14 way:

auto getNumberOfBuildings() const
{ return buildings.size(); }
like image 101
Andy Prowl Avatar answered Nov 15 '22 08:11

Andy Prowl


You should return a std::size_t. std::size_t is the return type of vector<T>::size() when you use the default allocator. vector<T>::size() returns vector<T>::size_type which is just a typedef for std::size_t when you use the default allocator (which you are most likely using).

like image 32
JKor Avatar answered Nov 15 '22 06:11

JKor