c++ - 在 C++ 中访问函数外部的数组

标签 c++ arrays

我有一个函数可以获取给定整数数组中的不同数字。我将不同的数字存储在另一个数组中,但我想访问 getUncommon 之外的不同数字,以便我可以进行一些比较和排序。

如果在 C++ 中不使用全局变量,这可能吗?

#include <iostream>

using namespace std;

void getUncommon(int* iAry, int size) {
    const int size2 = 10;
    int* tmpAry = new int[size2];
    int totalCount[size2] = { 0 };
    int currentCount[size2] = { 0 };
    int totalUncommon = 0;
    int i, j;
    int rareDigits[size2] = { 0 };

    for (i = 0; i < size; i++) {
        tmpAry[i] = iAry[i];
        if (tmpAry[i] < 0)
            tmpAry[i] *= -1;

        for (j = 0; j < size2; j++)
            currentCount[j] = 0;

        if (tmpAry[i] == 0) {
            currentCount[0] = 1;
        }

        while (tmpAry[i] / 10 != 0 || tmpAry[i] % 10 != 0){
            currentCount[tmpAry[i] % 10] = 1;
            tmpAry[i] /= 10;
        }

        for (j = 0; j < size2; j++) {
            totalCount[j] += currentCount[j];
        }
    }

    for (i = 0; i < size2; i++) {
        if (totalCount[i] == 1) {
            totalUncommon++;
        }
    }

    cout << "Total of uncommon digits: " << totalUncommon << endl
        << "Uncommon digits:\n";
    if (totalUncommon == 0) {
        cout << "\nNo uncommon digits found.";
    }
    else {
        for (i = 0; i < size2; i++) {
            if (totalCount[i] == 1) {
                cout << i << endl;
                rareDigits[i] = totalCount[i];
            }
        }
    }
    return;
}

int getNumRareDigits(int x) {
    // I would like to access rareDigits
    // so that I can pass in an integer
    // and see if it contains rareDigits[i] to
    // find the total number of rare digits.
}

int main(){
    int* my_arry;
    int size;
    int i;

    cout << "How many integers? ";
    cin >> size;

    for (i = 0; i < size; i++) {
        cout << "Enter values #" << i << " : ";
        cin >> size;
    }


    cout << "\nThe original array:" << endl;
    for (i = 0; i < size; i++) {
        cout << my_arry[i] << endl;
    }

    cout << "\nCalling function -\n" << endl;

    getUncommon(my_arry, size);


    return 0;
}

如何在 getUncommon 之外访问 rareDigits[i]

最佳答案

如果我正确理解你的问题,问题的真正核心是你想从外部范围访问局部变量。如果不使用全局变量,您的主要方法是传入要填充的数组。

例如,getUncommon 现在可能如下所示:

void getUncommon(int* iAry, int size, int* rare, int rareSize) { ...

现在,您将来可能需要考虑的一个问题是,如果事先不知道“稀有”数组的大小该怎么办。为了解决这个问题,您可能想要使用 int** (在 getUncommon 中分配数组)或更可能使用 std::vector& 之类的东西。

关于c++ - 在 C++ 中访问函数外部的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33115380/

相关文章:

c++ - Qt 中的错误:QMainWindowLayout::addItem:请改用公共(public) QMainWindow API

arrays - Bash 数组访问文件 Glob

python - 将对象列表转换为 numpy 数组的更快方法

python - ord() 预期长度为 1 的字符串,但找到了 int

c++ - 为什么具有非常量值的数组定义没有编译错误?

arrays - Matlab多项式拟合

c++ - 为什么wx这里不用引用,wx的API层和Port层是如何交互的?

c++ - 没有任何附加数据成员的派生类的大小

c++ - 访问实现接口(interface)但不属于接口(interface)的类的函数

c++ - 在C++中使用括号和方括号创建动态数组之间的区别