Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Which is correct for sizing a vector

Hi I am just starting to learn cpp and I have two examples of getting the size of a vector in the for statements both seem to work but which is right and why? sizeof(vector) or vector.size()?

Thanks

Brian

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void print_vector(vector<string> vector_to_print){
    cout << "\nCars vector = ";
    for(int i = 0; i < sizeof(vector_to_print); i++){
        cout << vector_to_print[i];
        (i < vector_to_print.size()-1) ? (cout << ", ") : (cout << endl); // ? the tenrary operator is an if statement (?) do one outcome (:) or the other
    }
}

void print_vector(vector <string> vector_to_print){
    cout << "\nVector contents = ";
    for( int i = 0; i < (vector_to_print.size()); i++ ){
        cout << vector_to_print[i];
        (i < (vector_to_print.size()-1)) ? (cout << ", ") : (cout << endl);
    }
}

Both seem to work I try to rewrite the same code from memory each day for a week to help me learn it and I couldn’t quite get the sizeof() to work so I googled it and the example I found used .size() but when I got home and checked what I did yesterday I had used sizeof().

>Solution :

As you already know there are classes in C++. One class can have many methods doing different things and many fields holding different things. When we create an object of class Vector this object has method .size() which as mentioned here returns the number of elements in our object. The complexity is Constant and there is no problem using .size().
When you are using sizeof() as mentioned here on our object you know the size of the object with all its fields (for example vector can have size_t field where it counts all the elements and some field which holds them) you don’t need the actual size of the vector in order to iterate the elements this could be wrong in many cases.

P.S. You must use .size()!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading