How do I find the length of an array?

前端 未结 27 2916
轮回少年
轮回少年 2020-11-21 23:10

Is there a way to find how many values an array has? Detecting whether or not I\'ve reached the end of an array would also work.

27条回答
  •  失恋的感觉
    2020-11-21 23:29

    There's also the TR1/C++11/C++17 way (see it Live on Coliru):

    const std::string s[3] = { "1"s, "2"s, "3"s };
    constexpr auto n       = std::extent<   decltype(s) >::value; // From 
    constexpr auto n2      = std::extent_v< decltype(s) >;        // C++17 shorthand
    
    const auto     a    = std::array{ "1"s, "2"s, "3"s };   // C++17 class template arg deduction -- http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
    constexpr auto size = std::tuple_size_v< decltype(a) >;
    
    std::cout << n << " " << n2 << " " << size << "\n"; // Prints 3 3 3
    

提交回复
热议问题