需要帮助返回2D数组C++

Need help with returning a 2D array C++, please

本文关键字:数组 C++ 2D 返回 帮助      更新时间:2023-10-16

我试图创建一个数组并将其传递给函数,然后函数返回它,但我不知道返回的正确方式。我一直在查阅教程并尝试一些东西,但一直没能解决这个问题。我是C++的新手,本以为它会类似于Java,但显然不是。

这就是我得到的:

class MainClass {
public:
    static int countLetterCombinations(string array[], int numberOfWords) {
        // Code
        return totalCombos;
    }

    // This is the function I'm having trouble with.
    static string** sortCombos(string combinations[][3]) {
            // Do something
        return combinations; // This gives converting error.
    }
};

int main() {
// Code
int numberOfCombinations = MainClass::countLetterCombinations(words, numberOfWords);
string combinations[numberOfCombinations][3];
combinations = MainClass::sortCombos(combinations);
// Further code
}

有人知道怎么解决这个问题吗?

您需要使用vector。基于C++堆栈的数组不能动态调整大小-哦,也不能将[][]转换为**,转换只适用于第一个维度。哦,你也不能分配给数组。

简单的规则是,在C++中,永远不要使用基元数组——它们只是一个令人头疼的问题。它们是从C继承而来的,C实际上定义了它的许多数组行为,以实现与B的源代码兼容性,而B已经非常古老了。使用为您管理动态内存的类,如std::vector,用于可动态扩展的阵列。

std::vector<std::array<std::string, 3>> combinations(numberOfCombinations);

static void sortCombos(std::vector<std::array<std::string, 3>>& combinations) {
        // Do something
} // This function modifies combinations in-place and doesn't require a return.

哦,你真的不必让函数成为静态类成员——它们可以放在全局命名空间中。

sortCombos方法可以在适当的位置修改数组参数,调用者将直接看到这些更改。因为您不需要返回任何内容,所以应该将返回类型更改为void。

即使可以返回输入数组,也不能分配给组合。