如何使用非类型模板参数传入指向数组的指针
How to use nontype template parameters to pass in a pointer to an array?
这段代码是我在动态编程中实现独木舟租赁问题的一部分。
我在堆上动态分配一个2-D数组,并将返回的地址保存到指向数组的指针类型的变量中。2-D矩阵本身是一个完美的N*N平方。我使用这种非正统的方法,因为数组是按行主顺序存储的,以便将其存储到缓存中。
然后,我想将指向数组的指针传递到一个函数中,以便填充该表。我使用了一个非类型模板参数,因为我可能正在传递一个指向不同大小数组的指针。我事先不知道矩阵的大小,这是由用户的输入决定的。
这是我的密码。我使用CCD_ 1是因为我知道矩阵中的每个值将是数字<256.
#include <cstdint> // for uint8_t
#include <cstdlib> // for size_t, EXIT_SUCCESS
#include <iostream>
#include <vector>
using std::cin;
using std::vector;
template <size_t num_of_stations>
void fillPrices(uint8_t (*&prices)[num_of_stations])
{
}
int main()
{
size_t num_of_stations = 0;
cin >> num_of_stations;
uint8_t (*prices)[num_of_stations] = static_cast<uint8_t(*)[num_of_stations]>( malloc(sizeof(uint8_t[num_of_stations][num_of_stations])) );
fillPrices(prices);
delete[] prices;
prices = nullptr;
return EXIT_SUCCESS;
}
我得到一个编译错误。应该对代码中的哪些内容进行更改以使其可编译?
canoe_rental.cpp: In function ‘int main()’:
canoe_rental.cpp:32:22: error: no matching function for call to ‘fillPrices(uint8_t (*&)[num_of_stations])’
fillPrices(prices);
^
canoe_rental.cpp:11:6: note: candidate: template<long unsigned int num_of_stations> void fillPrices(uint8_t (*&)[num_of_stations])
void fillPrices(uint8_t (*&prices)[num_of_stations])
^
canoe_rental.cpp:11:6: note: template argument deduction/substitution failed:
canoe_rental.cpp:32:22: note: variable-sized array type ‘long int’ is not a valid template argument
fillPrices(prices);
^
我认为非类型模板参数比它们的价值更麻烦。因此,我通过将指向数组的指针作为void*
传递,并传入指向数组中的元素数量,然后只使用类型转换来解决这个问题。现在,在身体内部,我可以按预期使用数组。它有点不优雅,但它很管用!
void fillPrices(void* ptr, size_t num_of_stations)
{
uint8_t (*prices)[num_of_stations] = static_cast<uint8_t(*)[num_of_stations]>(ptr);
}
// To call the function:
int main() {
// more code here
fillPrices(prices, num_of_stations);
}
相关文章:
- 添加到数组指针
- C++语法差异:二维和一维数组(指针算术)
- 数组指针表示法C++(移动数组时)
- 复制后删除原始数组指针将前 3 个字节设置为 0
- C++访问指向结构的指针中的类数组指针
- C++编译时使用 constexpr 字符数组指针分配静态数组?
- std::flush可以用于将对象指针转换为其封闭数组指针吗
- 创建<int>对整数数组指针的矢量引用 (C++)
- 将 2D 数组指针传递给 C++ 中的函数
- 创建指针是否超过非数组指针的末尾,而不是从 C++17 中的一元运算符和未定义的行为派生?
- 队列数组指针 (C++)
- C++数组指针上的删除操作
- 对于循环不循环和检测字符数组 [指针和字符数组]
- 如何初始化数组指针对象
- 如何正确传递 2D 数组指针作为参数
- 从数组指针中获取怪异的数字
- 初始化std :: unique_ptr作为原始数组指针的初始化
- 将结构数组指针从C#传递到C
- STD :: Sort将数组指针设置为NULL
- C++数组指针错误无法将“int*”转换为“int**”