I have tried this code in a Solaris envioronment and I have not got the out of range index exception.
This is my code:
template <typename T>
void setList(std::vector<T> & list)
{
srand(time(NULL));
int howMany, max, min;
std::cout << "How many items should be generated in the list? ";
std::cin >> howMany;
std::cin.ignore();
std::cout << "Max value of list? ";
std::cin >> max;
std::cin.ignore();
std::cout << "Min value of list? ";
std::cin >> min;
std::cin.ignore();
list.resize(howMany);
T randValue;
for (int i = 0; i < howMany; ++i)
{
randValue = (((T) rand() / (T) RAND_MAX) * (max - min)) + min;
list[i] = randValue;
}
// I Have added this feature for visualization purposes
for (int i = 0; i < list.size(); ++i)
{
std::cout << "list[" << i << "]=" << list[i] << std::endl;
}
}
And my main() looks like
int main(int argc, char** argv) {
std::vector<int> lista;
lista.clear();
setList(lista);
}
My output is:
By the way I have noticed that if you define a vector of integers, the content of the vector is always the min value. This is because you need to cast the intermediate values to double and cast finally the result to type T. (In the intege type the "/" operator is interpreted as an integer division).
You could do this.
for (int i = 0; i < howMany; ++i)
{
randValue = static_cast<T>((static_cast<double>((T) rand()) / static_cast<double>((T) RAND_MAX)) * (max - min)) + min;
list[i] = randValue;
}