vendredi 11 mars 2022

sizeof(std::vector

I'm confused between the sizeof(std::vector<T>) and sizeof(std::array<T, N>).

int main(int argc, char const *argv[]) {
    std::vector<int64_t> vec_1(2);
    std::cout << sizeof(vec_1) << std::endl;  // 24

    std::vector<int64_t> vec_2(5);
    std::cout << sizeof(vec_2) << std::endl;  // 24

    std::array<int64_t, 2> arr_1;
    std::cout << sizeof(arr_1) << std::endl;  // 16

    std::array<int64_t, 5> arr_2;
    std::cout << sizeof(arr_2) << std::endl;  // 40

    return 0;
}

As can be seen above sizeof(std::vector<T>) remains constant irrespective of a number of elements. However, that's not the case for sizeof(std::array<T, N>). Why? Both of them are STL containers.

Even for all the other STL containers like std::map<T1, T2>, std::unordered_map<T1, T2>, etc, I noticed that the output of sizeof remains constant irrespective of a total number of elements. Then why does for std::array<T, N>, it changes based on the number of elements? If that's how it's designed then why so?

Aucun commentaire:

Enregistrer un commentaire