有没有办法找出一个数组有多少个值?检测是否已经到达数组的末尾也可以工作。


当前回答

还有TR1/ c++ 11/ c++ 17方式(参见Coliru Live):

const std::string s[3] = { "1"s, "2"s, "3"s };
constexpr auto n       = std::extent<   decltype(s) >::value; // From <type_traits>
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

其他回答

只是一个想法,但只是决定创建一个计数器变量,并将数组大小存储在位置[0]。我删除了函数中的大部分代码,但你会看到退出循环后,prime[0]被分配为'a'的最终值。我尝试使用矢量,但VS Express 2013不太喜欢。还要注意,'a'从1开始,以避免覆盖[0],并在开始时初始化以避免错误。我不是专家,只是想分享一下。

int prime[] = {0};
int primes(int x, int y){
    using namespace std; int a = 1;
    for (int i = x; i <= y; i++){prime[a] = i; a++; }
    prime[0] = a; return 0;
}

还有TR1/ c++ 11/ c++ 17方式(参见Coliru Live):

const std::string s[3] = { "1"s, "2"s, "3"s };
constexpr auto n       = std::extent<   decltype(s) >::value; // From <type_traits>
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

而不是使用内置的数组函数aka:

 int x[3] = {0, 1, 2};

您应该使用数组类和数组模板。试一试:

#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};

现在如果你想求数组的长度,你所要做的就是使用数组类中的size函数。

Name_of_Array.size();

这应该返回数组中元素的长度。

我在这里提供了一个棘手的解决方案:

你总是可以在第一个元素中存储长度:

// malloc/new

arr[0] = length;
arr++;

// do anything. 
int len = *(arr-1);

free(--arr); 

代价是在调用free时必须—arr

我认为这是可行的:

for(int i=0;array[i];i++)
{
 //do_something
}