Home > Net >  Which is correct for sizing a vector
Which is correct for sizing a vector

Time:11-22

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

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().

CodePudding user response:

std::vector<std::string> is a container class, which stores an array of std::strings plus other values to assist with manipulation of the array and providing information about the state of the stored array. When you call sizeof(vector_to_print) you are simply getting the size of the container class not the amount of elements in the array that it is storing.

run the following code to prove it to yourself:

std::vector<std::string> vec{"hello","world"};
std::cout << sizeof(vec) << '\n';
vec.push_back("!");
std::cout << sizeof(vec);

the size of the underlying array is changing it goes from 2 elements to 3, but not only does the sizeof(vec) not change, it is always = to 24!

sizeof(vec) must be the same each time (24 bytes on my machine) because sizeof is a compile time constant, because the size of a type must be a compile time constant.

The latter (.size()) is the only valid method

CodePudding user response:

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()!

  • Related