Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector, Size_type, and Encapsulation

I have a class with a private data member of type vector< A*>.

The class has two public methods that actually use vector<A*>::size_type:

  1. Method returning number of elements in the vector
  2. Method returning element in the vector by index

I can add to public section of the class the following typedef:

typedef vector::size_type SIZE_t;

but IMHO it exposes too many details about class implementation.

Another approach is to use size_t.

What do you think?

like image 940
dimba Avatar asked Dec 09 '22 17:12

dimba


2 Answers

I would use a typedef in the class. The reason is that for std::vector, the size type is std::size_t, but if you later change the code to use a container (hand rolled) whose size type is not std::size_t redefining the typedef will be enough.

Using that typedef does not expose any detail of implementation, and it in fact helps encapsulate. The important element in the typedef is the local name, not what it is defined to be.

for ( mytype::size_type i = 0; i < myelement.size(); ++i )

In the for loop above, user code is unaware of whether size_type is a signed or unsigned type, it just works. You can change your implementation, and as long as you update the typedef the previous code will compile without signed/unsigned comparison warnings. The typedef actually helps encapsulation.

like image 118
David Rodríguez - dribeas Avatar answered Dec 17 '22 12:12

David Rodríguez - dribeas


Use plain old size_t for both member functions.

like image 25
dirkgently Avatar answered Dec 17 '22 11:12

dirkgently