Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

C++
// declare small vector
vector <int> smallVector(smallSize);
// call helper function to put random data in small vector
genRand(&smallVector, smallSize);



I get this error:

C++
Error	3	error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion)


code:
C++
// 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);
    }
}
Posted

Try leaving away the address-of operator while instantiating the function and pass the data in the template by reference.
Cheers
Andi
 
Share this answer
 
v2
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:

C++
template<typename T>
void genRand(T& data, int size)
{   
 ...


genRand(smallVector, smallSize);
genRand(smallArray, smallSize);

(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:

C++
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);

(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.
 
Share this answer
 
v8

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900