C++ vector size types

前端 未结 5 1840
醉话见心
醉话见心 2021-02-12 13:49

I just started learning C++ and have a question about vectors. The book I\'m reading states that if I want to extract the size of a vector of type double (for example), I should

5条回答
  •  [愿得一人]
    2021-02-12 13:59

    The book you’re reading states that if you want to extract the size of a vector of type double (for example), you should do something like:

        vector::size_type vector_size;
        vector_size = myVector.size();
    

    Whereas in Java you might do

        int vector_size;
        vector_size = myVector.size();
    

    Both are inferior options in C++. The first is extremely verbose and unsafe (mostly due to implicit promotions). The second is verbose and extremely unsafe (due to number range).

    In C++, do

        ptrdiff_t const vectorSize = myVector.size();
    

    Note that

    • ptrdiff_t, from the stddef.h header, is a signed type that is guaranteed large enough.

    • Initialization is done in the declaration (this is better C++ style).

    • The same naming convention has been applied to both variables.

    In summary, doing the right thing is shorter and safer.

    Cheers & hth.,

提交回复
热议问题