需要帮助返回2D数组C++
Need help with returning a 2D array C++, please
我试图创建一个数组并将其传递给函数,然后函数返回它,但我不知道返回的正确方式。我一直在查阅教程并尝试一些东西,但一直没能解决这个问题。我是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。
即使可以返回输入数组,也不能分配给组合。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '