如何实现接受向量和数组的模板函数 [英] How do you implement a template function that accepts vectors and arrays
问题描述
我试图将随机数分配给某个数组或向量
当我在数组上使用此方法时,它工作正常,但是当我将它与向量一起使用时,它将无法工作。
I am attempting to assign random numbers to some array or vector
When I use this method on an array it works fine, however when I use this with an vector, it will not work.
// declare small vector
vector <int> smallVector(smallSize);
// call helper function to put random data in small vector
genRand(&smallVector, smallSize);
我收到此错误:
I get this error:
Error 3 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)
代码:
code:
// function template for generating random numbers
template<class T> void genRand(T data, int size)
{
for (int i = 0; i < size; i++)
{
data[i] = (1 + rand() % size);
}
}
推荐答案
尝试在实例化函数时不要使用address-of运算符并通过引用传递模板中的数据。
干杯
Andi
Try leaving away the address-of operator while instantiating the function and pass the data in the template by reference.
Cheers
Andi
因为数据是一个超出参数(你是试图在genRand中填充它并在调用者中使结果可用,对吗?),你需要参考它:
Since data is an out-parameter (you're trying to populate it within genRand and make the result available in the caller, right?), you need to take it by reference:
template<typename T>
void genRand(T& data, int size)
{
...
genRand(smallVector, smallSize);
genRand(smallArray, smallSize);
(虽然在这种情况下你实际上不需要传递大小:http://coliru.stacked-crooked.com/a/b47b6b14ca97ea8d [ ^ ])
另外,你可以使用经典的C ++ 98迭代器接口:
(although you don't actually need to pass size in this case anymore: http://coliru.stacked-crooked.com/a/b47b6b14ca97ea8d[^])
Alternatively, you could use classic C++98 iterator interface:
template<typename Iter>
void genRand(Iter beg, Iter end, int size)
{
... // likely std::generate(beg, end, function);
genRand(smallVector.begin(), smallVector.end(), smallSize);
genRand(smallArray, smallArray + smallSize, smallSize);
(这也使得大小成为一个不必要的参数,它只是结束 - 请求)
在你的情况下发生的事情是你传递了一个指向矢量的指针,所以T被推导成一个指向矢量的指针,data [i]求值为向量,并且由于向量没有operator =接受int,因此您看到了错误消息。
(that also makes size an unnecessary parameter, it is simply end - beg)
What happened in your case was that you passed a pointer to the vector, so T was deduced to a pointer to a vector, data[i] evaluated to a vector, and since vector has no operator= that takes an int, you saw the error message.
这篇关于如何实现接受向量和数组的模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!