首页 > 解决方案 > 如何在 C++ 中创建一个数组长度的 int?

问题描述

所以基本上我正在尝试编写一个返回两倍数组长度的方法,但我无法弄清楚如何将长度变成一个 int 以便可以使用它。我一直在尝试找出正确的方法来使用,因为 sizeof() 返回字节数,而不是数组的长度。我应该使用什么方法以及如何解决这个问题?这是我的代码:

int main(int argc, const char * argv[]) {
    int arr[] = {1,2,3,4,5};
    cout << getLen(arr);
    return 0;
}

int getLen( int *arr ){
    int len = sizeof(arr);
    return 2 * len;
}

标签: c++arraysxcode

解决方案


我认为这可能是一个XY 问题。最终,如果您想在 C++ 中实现这种行为,您应该使用 std::vector 对象。例如:

#include <iostream>
#include <vector> // Remember to include this

int getLen(std::vector<int> &vec) // Pass vec by reference rather than as a pointer
{
    return static_cast<int>(vec.size()) * 2; // Use .size() to get the number of elements in vec
    // ^^^ .size() returns a value of type size_t which is converted to an int using static_cast<int>
}

int main()
{
    std::vector<int> vec = {1,2,3,4,5};

    std::cout << getLen(vec);

    return 0;
}

推荐阅读