Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Vector library, Recreating for Assignment, max size function

For an assignment I am supposed to recreate the C++ Vector library, and I am currently stuck on how to return maximum size.

According to this website: http://www.cplusplus.com/reference/stl/vector/ size_type max_size () const; Return maximum size

Returns the maximum number of elements that the vector container can hold.


Currently my functions are based on the manipulation of arrays and the vector library is not based on a template class, the vector library uses the int and size_t data-types. (I am unsure whether this has any bearing on it)

Relevant code:

class vector{
private:
int *vect;
size_t length;
size_t cap;

public:
//=====================Constructor================
vector(){
    length = 0;
    cap = 20;
    vect = new int[20];
}

//INCOMPLETE
size_t max_size() const{
    //return???!?!?!?!?
}

}

like image 581
Scott Curtis Avatar asked Feb 28 '12 02:02

Scott Curtis


2 Answers

From here in your link given:

but the maximum potential size the vector could reach due to system or library implementation limitations

In your case the max_size is the maximum size of an integer array on the system.

like image 24
devil Avatar answered Sep 21 '22 22:09

devil


This is pertaining to the max size due to limitations within your library/code or system. For a very contrived example, say your implementation used an unsigned short (2 byte) number to store the number of records in your vector. Then your max_size function would return 65,536 as your library would have this limitation due to poor implementation.

As another and more realistic example, if you knew that the maximum size of your vector in bytes was limited to 4G, and the size being contained within the container was 128 bytes per instance, then max_size would return something to the tune of 33,554,431. (0xFFFFFFFF / 128)

Below is how this is done in my implementation of C++. Essentially, finding the largest value of the size_type (unsigned being -1) then dividing that by the size of the object being stored within the vector. (value_type) On 32 bit hardware, the size_type(-1) will yield 4,294,967,295, and if you were storing an unsigned int your value sizeof(value_type) would yield 4 bytes giving you a max_size() return value of 1,073,741,823.

/**  Returns the size() of the largest possible %vector.  */
size_type max_size() const
{ 
    return size_type(-1) / sizeof(value_type); 
}
like image 89
RC. Avatar answered Sep 20 '22 22:09

RC.