【问题标题】:Why am I not able to find the length of those array in cpp [closed]为什么我无法在 cpp 中找到这些数组的长度 [关闭]
【发布时间】:2022-01-24 12:25:00
【问题描述】:

我正在尝试查找此数组的长度,并希望找到它的长度,以便我可以在 for 循环中使用它。

// importing needed libraries
#include <iostream>
#include <string>
#include <cmath>
#include <set>

// preventing need of std::cout, std::endl etc
using namespace std;


int main()
{
    int nums[] = {1, 2, 3, 4, 5, 6};

    int size;
    size = nums.size();

    cout << size;
    for (int i = 0; i < size; i++) 
    {
        cout << nums[i] << endl;
    }

    return 0;
}

使用 .size() 方法的行是导致问题的行

问题:-

error: member reference base type 'int [6]' is not a structure or union

据我了解,我对 .size() 的使用应该是正确的,但显然不是。

【问题讨论】:

  • .size()std::vectorstd::array 上的方法。普通 C++ 数组不支持方法调用
  • 您的理解从何而来?您可能误解了 C++ 教科书中的某些内容,您能引用教科书中的一段简短摘录让您相信这一点吗?
  • 我刚在google上搜索过

标签: c++ arrays for-loop iterator sizeof


【解决方案1】:

数组没有方法。所以这段代码sn-p是不正确的。

int size;
size = nums.size();

如果您的编译器支持 C++ 17,那么您可以包含头文件

#include <iterator>

然后写

size_t size = std::size( nums );

或者你甚至可以自己编写这样的函数,例如

template <size_t N>
size_t array_size( const int ( &a )[N] )
{
    return N;
} 

主要写

size_t size = array_size( nums );

另一种方法是包含标题

#include <type_traits>

然后写

size_t size = std::extent<decltype( nums )>::value;

或者你可以写

size_t size = sizeof( nums ) / sizeof( *nums );

注意输出数组时不需要知道它的大小。你可以写

for ( const auto &item : nums ) 
{
    cout << item << endl;
}

数组也可以使用迭代器输出

#include <iterator>

//...

for ( auto first = std::begin( nums ); first != std::end( nums ); ++first )
{
    cout << *first << endl;
}

使用迭代器还可以获取数组中的元素个数,例如

auto size = std::distance( std::begin( nums ), std::end( nums ) );

【讨论】:

    【解决方案2】:

    我还想提供另一种方式:

    #include <iostream>
    using namespace std;
    void solve()
    {
        int numbers[] = {1, 2, 3, 4, 5, 6};
        int numbersSize=0;
        for(int& item : numbers)
        {
            cout<<item<<", ";
            ++numbersSize;
        }
        cout<<endl<<"numbersSize <- "<<numbersSize<<endl;
        return;
    }
    int main()
    {
        solve();
        return 0;
    }
    

    结果如下:

    1, 2, 3, 4, 5, 6, 
    numbersSize <- 6
    

    所以,参数numbersSize的意义就是参数numbers的大小。

    【讨论】:

    • 为什么要在runtime计算编译器在compilation期间可以立即解决的问题?除此之外,你不能输出 before 迭代循环 - 不过这似乎是需要的。
    猜你喜欢
    • 2019-09-25
    • 2022-01-03
    • 2016-06-24
    • 2011-11-29
    • 2016-07-11
    • 2023-03-19
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多