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


当前回答

在c++中,使用std::array类来声明数组,可以很容易地找到数组的大小以及最后一个元素。

#include<iostream>
#include<array>
int main()
{
    std::array<int,3> arr;

    //To find the size of the array
    std::cout<<arr.size()<<std::endl;

    //Accessing the last element
    auto it=arr.end();
    std::cout<<arr.back()<<"\t"<<arr[arr.size()-1]<<"\t"<<*(--it);

    return 0;
}

事实上,数组类有很多其他函数,让我们使用数组作为标准容器。 参考1到c++ std::array类 引用2到std::array类 参考文献中的例子很有帮助。

其他回答

如果你指的是c风格的数组,那么你可以这样做:

int a[7];
std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;

这对指针不起作用(即它对以下任何一个都不起作用):

int *p = new int[7];
std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;

or:

void func(int *p)
{
    std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
}

int a[7];
func(a);

在c++中,如果你想要这种行为,那么你应该使用容器类;可能std::向量。

您可以使用sizeof()操作符,该操作符用于相同的目的。

请参阅下面的示例代码

#include <iostream>
using namespace std;
int main() {
  int arr[] = {10,20,30,40,50,60};
  int arrSize = sizeof(arr)/sizeof(arr[0]);
  cout << "The size of the array is: " << arrSize;
  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

有没有办法找出一个数组有多少个值?

Yes!

尝试sizeof(数组)/ sizeof(阵列[0])

检测是否已经到达数组的末尾也可以工作。

我看不到任何方法,除非你的数组是一个字符数组(即字符串)。

注:在c++中总是使用std::vector。有几个内置函数和一个扩展功能。

我个人建议(如果你因为任何原因无法使用专门的函数)首先扩展数组类型的兼容性,超出你通常使用它的范围(如果你存储的值≥0:

unsigned int x[] -> int x[]

你会让数组的元素比你需要的要大。对于最后一个元素,你可以放置一些类型,包括在扩展类型说明符中,但你通常不会使用,例如,使用前面的例子,最后一个元素将是-1。这使您能够(通过使用for循环)找到数组的最后一个元素。