简体   繁体   English

如何将函数的整数大小与数组的实际大小链接? C ++

[英]How do i link the integer size of the function with the actual size of an array? C++

I'm trying to write a function that calculates the sum of an array, but when i declare int size = 0; 我正在尝试编写一个计算数组总和的函数,但是当我声明int size = 0时; , the function runs 0 times because i=0 ; ,该函数运行0次,因为i = 0; i 一世

int arraChec(int arra[]) {

    int size = 0;
    int sum = 0;

    for (int i = 0; i < size; i++) {
        sum = sum + arra[i];
    }
    return sum;
}


int main() {

    int arra1[7] = { 2,3,5,7,8,9,1 };

    cout << arraChec(arra1) << endl;

    system("pause");
}

You need to pass two arguments to the function--either the beginning of the array plus the size, or the beginning and (one past the) end, as is conventional in C++: 您需要将两个参数传递给函数-像C ++中常规的那样,要么是数组的开头加上大小,要么是开头和结尾(结尾处是一个)。

int arraChec(int* begin, int* end) {
    int sum = 0;
    for (int* it = begin; it < end; ++it) {
        sum += *it;
    }
    return sum;
}

int main() {

    int arra1[7] = { 2,3,5,7,8,9,1 };

    cout << arraChec(std::begin(arra1), std::end(arra1)) << endl;

    system("pause");
}

Of course, you can implement is using the standard library: 当然,您可以使用标准库来实现:

cout << std::accumulate(std::begin(arra1), std::end(arra1), 0) << endl;

Pass in the array size as a parameter: 传入数组大小作为参数:

#include <iostream>
int arraChec(int arra[], int size) {
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arra[i];
    }
    return sum;
}
int main() {
    int arra1[7] = { 2, 3, 5, 7, 8, 9, 1 };
    std::cout << arraChec(arra1, 7) << std::endl;
}

Or use std::vector : 或使用std::vector

#include <iostream>
#include <vector>

int arraChec(std::vector<int>& arra) {
    int sum = 0;
    for (int i = 0; i < arra.size(); i++) {
        sum += arra[i];
    }
    return sum;
}

int main() {
    std::vector<int> arra1 = { 2, 3, 5, 7, 8, 9, 1 };
    std::cout << arraChec(arra1) << std::endl;
}

If you are referring to some C style (sizeof(arra) / sizeof(*arra)) construct I suggest you refrain from using it. 如果您指的是某些C样式(sizeof(arra) / sizeof(*arra))构造,我建议您不要使用它。

Use std::array instead of fixed size C-style array. 使用std::array而不是固定大小的C样式数组。

#include <iostream>
#include <array>
#include <numeric>
using namespace std;

int main() {
    array<int, 7> arr = { 2, 3, 5, 7, 8, 9, 1 };
    cout << accumulate(arr.begin(), arr.end(), 0) << endl;
    return 0;
}

Output 产量

35

Read more about std::accumulate . 了解更多有关std::accumulate

Another way not mentioned yet is: 尚未提及的另一种方法是:

template<size_t N>
int arraChec(int (&arra)[N]) {
    int sum = 0;

    for (size_t i = 0; i < N; i++) {
        sum = sum + arra[i];
    }
    return sum;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM