Search code examples
c++vectorsizesizeof

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

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

  • 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