How to generate random numbers to populate a dynamic array according to the template type?Why can templates only be implemented in the header file?How to generate a random alpha-numeric string?How to generate a random string in RubyGenerating random numbers in Objective-CHow to get a random number in RubyHow do I generate random integers within a specific range in Java?Random number generator only generating one random numberHow can I generate random alphanumeric strings?Generating random whole numbers in JavaScript in a specific range?How do I generate a random int number?Generate random number between two numbers in JavaScript

C++ copy constructor called at return

Why should universal income be universal?

What is the English pronunciation of "pain au chocolat"?

Why do some congregations only make noise at certain occasions of Haman?

15% tax on $7.5k earnings. Is that right?

Make a Bowl of Alphabet Soup

Strong empirical falsification of quantum mechanics based on vacuum energy density?

Does Doodling or Improvising on the Piano Have Any Benefits?

US tourist/student visa

Pre-mixing cryogenic fuels and using only one fuel tank

Why is it that I can sometimes guess the next note?

Change the color of a single dot in `ddot` symbol

Is this toilet slogan correct usage of the English language?

Is there any evidence that Cleopatra and Caesarion considered fleeing to India to escape the Romans?

Mimic lecturing on blackboard, facing audience

How to make money from a browser who sees 5 seconds into the future of any web page?

How to get directions in deep space?

How to convince somebody that he is fit for something else, but not this job?

Review your own paper in Mathematics

Is there a way to have vectors outlined in a Vector Plot?

Creating two special characters

Can I cause damage to electrical appliances by unplugging them when they are turned on?

What kind of floor tile is this?

Giving feedback to someone without sounding prejudiced



How to generate random numbers to populate a dynamic array according to the template type?


Why can templates only be implemented in the header file?How to generate a random alpha-numeric string?How to generate a random string in RubyGenerating random numbers in Objective-CHow to get a random number in RubyHow do I generate random integers within a specific range in Java?Random number generator only generating one random numberHow can I generate random alphanumeric strings?Generating random whole numbers in JavaScript in a specific range?How do I generate a random int number?Generate random number between two numbers in JavaScript













-3















I've been focusing on my latest programming exercise to implement templates to print out 2D arrays. I am only allowed to modify the implementation files. (i.e. main and the header files have to remain untouched) I got stuck on populating the arrays using random numbers according to the template type the object takes. Is there a viable way to utilize rand() to generate random numbers according to the type? Any help will be appreciated. Thanks!



 RowAray.h:
#ifndef ROWARAY_H
#define ROWARAY_H
template<class T>
class RowAray
protected:
int size;
T *rowData;
public:
RowAray(int);
virtual ~RowAray();
int getSize()constreturn size;
T getData(int i)const
if(i>=0&&i<size)return rowData[i];
else return 0;
void setData(int,T);
;


#endif /* ROWARAY_H */

Table.h:
#ifndef TABLE_H
#define TABLE_H
#include "RowAray.h"

template<class T>
class Table
protected:
int szRow;
int szCol;
RowAray<T> **columns;
public:
Table(unsigned int,unsigned int);
Table(const Table<T> &);
virtual ~Table();
int getSzRow()const return szRow;
int getSzCol()const return szCol;
T getData(int,int)const;
void setData(int,int,T);
Table<T> operator+(const Table<T> &);
;

#endif /* TABLE_H */

RowAray.cpp:
#include "RowAray.h"
#include <cstdlib>


template<class T>
RowAray<T>::RowAray(int r)
size = r;

rowData = new T[r];

for (int i = 0; i < size; i++)
rowData[i] = static_cast<T>((rand() % 90 + 10));



template<class T>
RowAray<T>::~RowAray()
delete []rowData;


template<class T>
void RowAray<T>::setData(int i, T value)
rowData[i] = value;



Table.cpp:
#include "Table.h"

template<class T>
Table<T>::Table(unsigned int r, unsigned int c)
szRow = r;
szCol = c;

columns = new RowAray<T>*[r];

for(int i = 0; i < r; i++)
columns[i] = new RowAray<T>(c);



template<class T>
Table<T>::Table(const Table<T> &t)
szRow = t.getSzRow();
szCol = t.getSzCol();

columns = new RowAray<T>*[t.getSzRow()];

for(int i = 0; i < t.getSzRow(); i++)
columns[i] = new RowAray<T>(t.getSzCol());


for (int i = 0; i < t.getSzRow(); i++)
for (int j = 0; j < t.getSzCol(); j++)
columns[i]->setData(j, t.getData(i, j));




template<class T>
Table<T>::~Table()
for (int i = 0; i < szRow; i++)
delete []columns[i];

delete []columns;


template<class T>
Table<T> Table<T>:: operator+(const Table<T> &t)
Table<T> tab;

tab.szRow = t.getSzRow();
tab.szCol = t.getSzCol();

for(int i = 0; i < t.getSzRow(); i++)
for (int j = 0; j <t.getSzCol(); j++)
tab.columns[i]->setData(j, this->getData(i,j) + t.getData(i,j));



return tab;


main.cpp:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
using namespace std;

//User Libraries
#include "Table.h"

//Global Constants

//Function Prototype
template<class T>
void prntRow(RowAray<T> *,int);
template<class T>
void prntTab(const Table<T> &);

//Execution Begins Here!
int main(int argc, char** argv)
//Initialize the random seed
srand(static_cast<unsigned int>(time(0)));

//Declare Variables
int rows=3,cols=4;

//Test out the Row with integers and floats
RowAray<int> a(3);RowAray<float> b(4);
cout<<"Test the Integer Row "<<endl;
prntRow(&a,3);
cout<<"Test the Float Row "<<endl;
prntRow(&b,4);

//Test out the Table with a float
Table<float> tab1(rows,cols);
Table<float> tab2(tab1);
Table<float> tab3=tab1+tab2;

cout<<"Float Table 1 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab1);

cout<<"Float Table 2 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab2);

cout<<"Float Table 3 size is [row,col] = Table 1 + Table 2 ["
<<rows<<","<<cols<<"]";
prntTab(tab3);

//Exit Stage Right
return 0;


template<class T>
void prntRow(RowAray<T> *a,int perLine)
cout<<fixed<<setprecision(1)<<showpoint<<endl;
for(int i=0;i<a->getSize();i++)
cout<<a->getData(i)<<" ";
if(i%perLine==(perLine-1))cout<<endl;

cout<<endl;


template<class T>
void prntTab(const Table<T> &a)
cout<<fixed<<setprecision(1)<<showpoint<<endl;
for(int row=0;row<a.getSzRow();row++)
for(int col=0;col<a.getSzCol();col++)
cout<<setw(8)<<a.getData(row,col);

cout<<endl;

cout<<endl;










share|improve this question

















  • 2





    There is a lot of code here, you will get better answers if you can reduce it to the key details. See stackoverflow.com/help/how-to-ask

    – Simon.S.A.
    Mar 8 at 0:00











  • What are the problems you are experiencing?

    – Rick Pat
    Mar 8 at 0:01











  • See #include <random>

    – Sailanarmo
    Mar 8 at 0:13











  • You may want to think about what you want to ask some more. What does "generate random numbers according to the type" mean? The type is is supposed to affect which random numbers are generated? If it's supposed to mean something more like "generate random numbers and cast them to the type", what's supposed to happen if, for example, the type is std::nullptr_t?

    – JaMiT
    Mar 8 at 5:20











  • If I'm reading things right, this question is about how to use rand() to accomplish something involving a templated type. How much of your code is relevant to the precise question being asked? Couldn't you trim off like 90% of that code to get a Minimal, Complete, and Verifiable example showing just the scenario that uses rand()?

    – JaMiT
    Mar 8 at 5:25















-3















I've been focusing on my latest programming exercise to implement templates to print out 2D arrays. I am only allowed to modify the implementation files. (i.e. main and the header files have to remain untouched) I got stuck on populating the arrays using random numbers according to the template type the object takes. Is there a viable way to utilize rand() to generate random numbers according to the type? Any help will be appreciated. Thanks!



 RowAray.h:
#ifndef ROWARAY_H
#define ROWARAY_H
template<class T>
class RowAray
protected:
int size;
T *rowData;
public:
RowAray(int);
virtual ~RowAray();
int getSize()constreturn size;
T getData(int i)const
if(i>=0&&i<size)return rowData[i];
else return 0;
void setData(int,T);
;


#endif /* ROWARAY_H */

Table.h:
#ifndef TABLE_H
#define TABLE_H
#include "RowAray.h"

template<class T>
class Table
protected:
int szRow;
int szCol;
RowAray<T> **columns;
public:
Table(unsigned int,unsigned int);
Table(const Table<T> &);
virtual ~Table();
int getSzRow()const return szRow;
int getSzCol()const return szCol;
T getData(int,int)const;
void setData(int,int,T);
Table<T> operator+(const Table<T> &);
;

#endif /* TABLE_H */

RowAray.cpp:
#include "RowAray.h"
#include <cstdlib>


template<class T>
RowAray<T>::RowAray(int r)
size = r;

rowData = new T[r];

for (int i = 0; i < size; i++)
rowData[i] = static_cast<T>((rand() % 90 + 10));



template<class T>
RowAray<T>::~RowAray()
delete []rowData;


template<class T>
void RowAray<T>::setData(int i, T value)
rowData[i] = value;



Table.cpp:
#include "Table.h"

template<class T>
Table<T>::Table(unsigned int r, unsigned int c)
szRow = r;
szCol = c;

columns = new RowAray<T>*[r];

for(int i = 0; i < r; i++)
columns[i] = new RowAray<T>(c);



template<class T>
Table<T>::Table(const Table<T> &t)
szRow = t.getSzRow();
szCol = t.getSzCol();

columns = new RowAray<T>*[t.getSzRow()];

for(int i = 0; i < t.getSzRow(); i++)
columns[i] = new RowAray<T>(t.getSzCol());


for (int i = 0; i < t.getSzRow(); i++)
for (int j = 0; j < t.getSzCol(); j++)
columns[i]->setData(j, t.getData(i, j));




template<class T>
Table<T>::~Table()
for (int i = 0; i < szRow; i++)
delete []columns[i];

delete []columns;


template<class T>
Table<T> Table<T>:: operator+(const Table<T> &t)
Table<T> tab;

tab.szRow = t.getSzRow();
tab.szCol = t.getSzCol();

for(int i = 0; i < t.getSzRow(); i++)
for (int j = 0; j <t.getSzCol(); j++)
tab.columns[i]->setData(j, this->getData(i,j) + t.getData(i,j));



return tab;


main.cpp:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
using namespace std;

//User Libraries
#include "Table.h"

//Global Constants

//Function Prototype
template<class T>
void prntRow(RowAray<T> *,int);
template<class T>
void prntTab(const Table<T> &);

//Execution Begins Here!
int main(int argc, char** argv)
//Initialize the random seed
srand(static_cast<unsigned int>(time(0)));

//Declare Variables
int rows=3,cols=4;

//Test out the Row with integers and floats
RowAray<int> a(3);RowAray<float> b(4);
cout<<"Test the Integer Row "<<endl;
prntRow(&a,3);
cout<<"Test the Float Row "<<endl;
prntRow(&b,4);

//Test out the Table with a float
Table<float> tab1(rows,cols);
Table<float> tab2(tab1);
Table<float> tab3=tab1+tab2;

cout<<"Float Table 1 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab1);

cout<<"Float Table 2 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab2);

cout<<"Float Table 3 size is [row,col] = Table 1 + Table 2 ["
<<rows<<","<<cols<<"]";
prntTab(tab3);

//Exit Stage Right
return 0;


template<class T>
void prntRow(RowAray<T> *a,int perLine)
cout<<fixed<<setprecision(1)<<showpoint<<endl;
for(int i=0;i<a->getSize();i++)
cout<<a->getData(i)<<" ";
if(i%perLine==(perLine-1))cout<<endl;

cout<<endl;


template<class T>
void prntTab(const Table<T> &a)
cout<<fixed<<setprecision(1)<<showpoint<<endl;
for(int row=0;row<a.getSzRow();row++)
for(int col=0;col<a.getSzCol();col++)
cout<<setw(8)<<a.getData(row,col);

cout<<endl;

cout<<endl;










share|improve this question

















  • 2





    There is a lot of code here, you will get better answers if you can reduce it to the key details. See stackoverflow.com/help/how-to-ask

    – Simon.S.A.
    Mar 8 at 0:00











  • What are the problems you are experiencing?

    – Rick Pat
    Mar 8 at 0:01











  • See #include <random>

    – Sailanarmo
    Mar 8 at 0:13











  • You may want to think about what you want to ask some more. What does "generate random numbers according to the type" mean? The type is is supposed to affect which random numbers are generated? If it's supposed to mean something more like "generate random numbers and cast them to the type", what's supposed to happen if, for example, the type is std::nullptr_t?

    – JaMiT
    Mar 8 at 5:20











  • If I'm reading things right, this question is about how to use rand() to accomplish something involving a templated type. How much of your code is relevant to the precise question being asked? Couldn't you trim off like 90% of that code to get a Minimal, Complete, and Verifiable example showing just the scenario that uses rand()?

    – JaMiT
    Mar 8 at 5:25













-3












-3








-3


0






I've been focusing on my latest programming exercise to implement templates to print out 2D arrays. I am only allowed to modify the implementation files. (i.e. main and the header files have to remain untouched) I got stuck on populating the arrays using random numbers according to the template type the object takes. Is there a viable way to utilize rand() to generate random numbers according to the type? Any help will be appreciated. Thanks!



 RowAray.h:
#ifndef ROWARAY_H
#define ROWARAY_H
template<class T>
class RowAray
protected:
int size;
T *rowData;
public:
RowAray(int);
virtual ~RowAray();
int getSize()constreturn size;
T getData(int i)const
if(i>=0&&i<size)return rowData[i];
else return 0;
void setData(int,T);
;


#endif /* ROWARAY_H */

Table.h:
#ifndef TABLE_H
#define TABLE_H
#include "RowAray.h"

template<class T>
class Table
protected:
int szRow;
int szCol;
RowAray<T> **columns;
public:
Table(unsigned int,unsigned int);
Table(const Table<T> &);
virtual ~Table();
int getSzRow()const return szRow;
int getSzCol()const return szCol;
T getData(int,int)const;
void setData(int,int,T);
Table<T> operator+(const Table<T> &);
;

#endif /* TABLE_H */

RowAray.cpp:
#include "RowAray.h"
#include <cstdlib>


template<class T>
RowAray<T>::RowAray(int r)
size = r;

rowData = new T[r];

for (int i = 0; i < size; i++)
rowData[i] = static_cast<T>((rand() % 90 + 10));



template<class T>
RowAray<T>::~RowAray()
delete []rowData;


template<class T>
void RowAray<T>::setData(int i, T value)
rowData[i] = value;



Table.cpp:
#include "Table.h"

template<class T>
Table<T>::Table(unsigned int r, unsigned int c)
szRow = r;
szCol = c;

columns = new RowAray<T>*[r];

for(int i = 0; i < r; i++)
columns[i] = new RowAray<T>(c);



template<class T>
Table<T>::Table(const Table<T> &t)
szRow = t.getSzRow();
szCol = t.getSzCol();

columns = new RowAray<T>*[t.getSzRow()];

for(int i = 0; i < t.getSzRow(); i++)
columns[i] = new RowAray<T>(t.getSzCol());


for (int i = 0; i < t.getSzRow(); i++)
for (int j = 0; j < t.getSzCol(); j++)
columns[i]->setData(j, t.getData(i, j));




template<class T>
Table<T>::~Table()
for (int i = 0; i < szRow; i++)
delete []columns[i];

delete []columns;


template<class T>
Table<T> Table<T>:: operator+(const Table<T> &t)
Table<T> tab;

tab.szRow = t.getSzRow();
tab.szCol = t.getSzCol();

for(int i = 0; i < t.getSzRow(); i++)
for (int j = 0; j <t.getSzCol(); j++)
tab.columns[i]->setData(j, this->getData(i,j) + t.getData(i,j));



return tab;


main.cpp:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
using namespace std;

//User Libraries
#include "Table.h"

//Global Constants

//Function Prototype
template<class T>
void prntRow(RowAray<T> *,int);
template<class T>
void prntTab(const Table<T> &);

//Execution Begins Here!
int main(int argc, char** argv)
//Initialize the random seed
srand(static_cast<unsigned int>(time(0)));

//Declare Variables
int rows=3,cols=4;

//Test out the Row with integers and floats
RowAray<int> a(3);RowAray<float> b(4);
cout<<"Test the Integer Row "<<endl;
prntRow(&a,3);
cout<<"Test the Float Row "<<endl;
prntRow(&b,4);

//Test out the Table with a float
Table<float> tab1(rows,cols);
Table<float> tab2(tab1);
Table<float> tab3=tab1+tab2;

cout<<"Float Table 1 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab1);

cout<<"Float Table 2 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab2);

cout<<"Float Table 3 size is [row,col] = Table 1 + Table 2 ["
<<rows<<","<<cols<<"]";
prntTab(tab3);

//Exit Stage Right
return 0;


template<class T>
void prntRow(RowAray<T> *a,int perLine)
cout<<fixed<<setprecision(1)<<showpoint<<endl;
for(int i=0;i<a->getSize();i++)
cout<<a->getData(i)<<" ";
if(i%perLine==(perLine-1))cout<<endl;

cout<<endl;


template<class T>
void prntTab(const Table<T> &a)
cout<<fixed<<setprecision(1)<<showpoint<<endl;
for(int row=0;row<a.getSzRow();row++)
for(int col=0;col<a.getSzCol();col++)
cout<<setw(8)<<a.getData(row,col);

cout<<endl;

cout<<endl;










share|improve this question














I've been focusing on my latest programming exercise to implement templates to print out 2D arrays. I am only allowed to modify the implementation files. (i.e. main and the header files have to remain untouched) I got stuck on populating the arrays using random numbers according to the template type the object takes. Is there a viable way to utilize rand() to generate random numbers according to the type? Any help will be appreciated. Thanks!



 RowAray.h:
#ifndef ROWARAY_H
#define ROWARAY_H
template<class T>
class RowAray
protected:
int size;
T *rowData;
public:
RowAray(int);
virtual ~RowAray();
int getSize()constreturn size;
T getData(int i)const
if(i>=0&&i<size)return rowData[i];
else return 0;
void setData(int,T);
;


#endif /* ROWARAY_H */

Table.h:
#ifndef TABLE_H
#define TABLE_H
#include "RowAray.h"

template<class T>
class Table
protected:
int szRow;
int szCol;
RowAray<T> **columns;
public:
Table(unsigned int,unsigned int);
Table(const Table<T> &);
virtual ~Table();
int getSzRow()const return szRow;
int getSzCol()const return szCol;
T getData(int,int)const;
void setData(int,int,T);
Table<T> operator+(const Table<T> &);
;

#endif /* TABLE_H */

RowAray.cpp:
#include "RowAray.h"
#include <cstdlib>


template<class T>
RowAray<T>::RowAray(int r)
size = r;

rowData = new T[r];

for (int i = 0; i < size; i++)
rowData[i] = static_cast<T>((rand() % 90 + 10));



template<class T>
RowAray<T>::~RowAray()
delete []rowData;


template<class T>
void RowAray<T>::setData(int i, T value)
rowData[i] = value;



Table.cpp:
#include "Table.h"

template<class T>
Table<T>::Table(unsigned int r, unsigned int c)
szRow = r;
szCol = c;

columns = new RowAray<T>*[r];

for(int i = 0; i < r; i++)
columns[i] = new RowAray<T>(c);



template<class T>
Table<T>::Table(const Table<T> &t)
szRow = t.getSzRow();
szCol = t.getSzCol();

columns = new RowAray<T>*[t.getSzRow()];

for(int i = 0; i < t.getSzRow(); i++)
columns[i] = new RowAray<T>(t.getSzCol());


for (int i = 0; i < t.getSzRow(); i++)
for (int j = 0; j < t.getSzCol(); j++)
columns[i]->setData(j, t.getData(i, j));




template<class T>
Table<T>::~Table()
for (int i = 0; i < szRow; i++)
delete []columns[i];

delete []columns;


template<class T>
Table<T> Table<T>:: operator+(const Table<T> &t)
Table<T> tab;

tab.szRow = t.getSzRow();
tab.szCol = t.getSzCol();

for(int i = 0; i < t.getSzRow(); i++)
for (int j = 0; j <t.getSzCol(); j++)
tab.columns[i]->setData(j, this->getData(i,j) + t.getData(i,j));



return tab;


main.cpp:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
using namespace std;

//User Libraries
#include "Table.h"

//Global Constants

//Function Prototype
template<class T>
void prntRow(RowAray<T> *,int);
template<class T>
void prntTab(const Table<T> &);

//Execution Begins Here!
int main(int argc, char** argv)
//Initialize the random seed
srand(static_cast<unsigned int>(time(0)));

//Declare Variables
int rows=3,cols=4;

//Test out the Row with integers and floats
RowAray<int> a(3);RowAray<float> b(4);
cout<<"Test the Integer Row "<<endl;
prntRow(&a,3);
cout<<"Test the Float Row "<<endl;
prntRow(&b,4);

//Test out the Table with a float
Table<float> tab1(rows,cols);
Table<float> tab2(tab1);
Table<float> tab3=tab1+tab2;

cout<<"Float Table 1 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab1);

cout<<"Float Table 2 size is [row,col] = ["
<<rows<<","<<cols<<"]";
prntTab(tab2);

cout<<"Float Table 3 size is [row,col] = Table 1 + Table 2 ["
<<rows<<","<<cols<<"]";
prntTab(tab3);

//Exit Stage Right
return 0;


template<class T>
void prntRow(RowAray<T> *a,int perLine)
cout<<fixed<<setprecision(1)<<showpoint<<endl;
for(int i=0;i<a->getSize();i++)
cout<<a->getData(i)<<" ";
if(i%perLine==(perLine-1))cout<<endl;

cout<<endl;


template<class T>
void prntTab(const Table<T> &a)
cout<<fixed<<setprecision(1)<<showpoint<<endl;
for(int row=0;row<a.getSzRow();row++)
for(int col=0;col<a.getSzCol();col++)
cout<<setw(8)<<a.getData(row,col);

cout<<endl;

cout<<endl;







c++ templates random netbeans






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 7 at 23:58









V.ReeveV.Reeve

11




11







  • 2





    There is a lot of code here, you will get better answers if you can reduce it to the key details. See stackoverflow.com/help/how-to-ask

    – Simon.S.A.
    Mar 8 at 0:00











  • What are the problems you are experiencing?

    – Rick Pat
    Mar 8 at 0:01











  • See #include <random>

    – Sailanarmo
    Mar 8 at 0:13











  • You may want to think about what you want to ask some more. What does "generate random numbers according to the type" mean? The type is is supposed to affect which random numbers are generated? If it's supposed to mean something more like "generate random numbers and cast them to the type", what's supposed to happen if, for example, the type is std::nullptr_t?

    – JaMiT
    Mar 8 at 5:20











  • If I'm reading things right, this question is about how to use rand() to accomplish something involving a templated type. How much of your code is relevant to the precise question being asked? Couldn't you trim off like 90% of that code to get a Minimal, Complete, and Verifiable example showing just the scenario that uses rand()?

    – JaMiT
    Mar 8 at 5:25












  • 2





    There is a lot of code here, you will get better answers if you can reduce it to the key details. See stackoverflow.com/help/how-to-ask

    – Simon.S.A.
    Mar 8 at 0:00











  • What are the problems you are experiencing?

    – Rick Pat
    Mar 8 at 0:01











  • See #include <random>

    – Sailanarmo
    Mar 8 at 0:13











  • You may want to think about what you want to ask some more. What does "generate random numbers according to the type" mean? The type is is supposed to affect which random numbers are generated? If it's supposed to mean something more like "generate random numbers and cast them to the type", what's supposed to happen if, for example, the type is std::nullptr_t?

    – JaMiT
    Mar 8 at 5:20











  • If I'm reading things right, this question is about how to use rand() to accomplish something involving a templated type. How much of your code is relevant to the precise question being asked? Couldn't you trim off like 90% of that code to get a Minimal, Complete, and Verifiable example showing just the scenario that uses rand()?

    – JaMiT
    Mar 8 at 5:25







2




2





There is a lot of code here, you will get better answers if you can reduce it to the key details. See stackoverflow.com/help/how-to-ask

– Simon.S.A.
Mar 8 at 0:00





There is a lot of code here, you will get better answers if you can reduce it to the key details. See stackoverflow.com/help/how-to-ask

– Simon.S.A.
Mar 8 at 0:00













What are the problems you are experiencing?

– Rick Pat
Mar 8 at 0:01





What are the problems you are experiencing?

– Rick Pat
Mar 8 at 0:01













See #include <random>

– Sailanarmo
Mar 8 at 0:13





See #include <random>

– Sailanarmo
Mar 8 at 0:13













You may want to think about what you want to ask some more. What does "generate random numbers according to the type" mean? The type is is supposed to affect which random numbers are generated? If it's supposed to mean something more like "generate random numbers and cast them to the type", what's supposed to happen if, for example, the type is std::nullptr_t?

– JaMiT
Mar 8 at 5:20





You may want to think about what you want to ask some more. What does "generate random numbers according to the type" mean? The type is is supposed to affect which random numbers are generated? If it's supposed to mean something more like "generate random numbers and cast them to the type", what's supposed to happen if, for example, the type is std::nullptr_t?

– JaMiT
Mar 8 at 5:20













If I'm reading things right, this question is about how to use rand() to accomplish something involving a templated type. How much of your code is relevant to the precise question being asked? Couldn't you trim off like 90% of that code to get a Minimal, Complete, and Verifiable example showing just the scenario that uses rand()?

– JaMiT
Mar 8 at 5:25





If I'm reading things right, this question is about how to use rand() to accomplish something involving a templated type. How much of your code is relevant to the precise question being asked? Couldn't you trim off like 90% of that code to get a Minimal, Complete, and Verifiable example showing just the scenario that uses rand()?

– JaMiT
Mar 8 at 5:25












1 Answer
1






active

oldest

votes


















0














Not entirely clear from your question, but assuming you want to generate random values in different ways for different types, you can use specialization of a template function:



template <class T>
T random_value(); // no definition

template <>
float random_value<float>()

return float(random()) / RAND_MAX; // number in [0, 1)


template <>
int random_value<int>()

return random();


template <>
uint64_t random_value<uint64_t>()
uint32_t(random());



And then inside RowArray::RowArray you would simply use:



rowdata[i] = random_value<T>();


To factor related specializations together (for example all integral types), take a look at std::enable_if.



A second way you might do this is in C++17 is with if constexpr and std::is_same_v. For example, inside your RowArray::RowArray constructor, you can do something like this:



for (int i = 0; i < size; ++i)

if constexpr (std::is_same_v<T, float>)
row[i] = /* whatever you want for float case */
else if constexpr (std::is_same_v<T, int>)
row[i] = /* whatever you want for int case*/
else
static_assert(sizeof(T) == 0, "unsupported type");



Take a look at the type_traits header to see how to test for all integral types etc.



Finally, take a look at C++ random library http://www.cplusplus.com/reference/random/ to avoid making common mistakes when working with random values.






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55054728%2fhow-to-generate-random-numbers-to-populate-a-dynamic-array-according-to-the-temp%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Not entirely clear from your question, but assuming you want to generate random values in different ways for different types, you can use specialization of a template function:



    template <class T>
    T random_value(); // no definition

    template <>
    float random_value<float>()

    return float(random()) / RAND_MAX; // number in [0, 1)


    template <>
    int random_value<int>()

    return random();


    template <>
    uint64_t random_value<uint64_t>()
    uint32_t(random());



    And then inside RowArray::RowArray you would simply use:



    rowdata[i] = random_value<T>();


    To factor related specializations together (for example all integral types), take a look at std::enable_if.



    A second way you might do this is in C++17 is with if constexpr and std::is_same_v. For example, inside your RowArray::RowArray constructor, you can do something like this:



    for (int i = 0; i < size; ++i)

    if constexpr (std::is_same_v<T, float>)
    row[i] = /* whatever you want for float case */
    else if constexpr (std::is_same_v<T, int>)
    row[i] = /* whatever you want for int case*/
    else
    static_assert(sizeof(T) == 0, "unsupported type");



    Take a look at the type_traits header to see how to test for all integral types etc.



    Finally, take a look at C++ random library http://www.cplusplus.com/reference/random/ to avoid making common mistakes when working with random values.






    share|improve this answer



























      0














      Not entirely clear from your question, but assuming you want to generate random values in different ways for different types, you can use specialization of a template function:



      template <class T>
      T random_value(); // no definition

      template <>
      float random_value<float>()

      return float(random()) / RAND_MAX; // number in [0, 1)


      template <>
      int random_value<int>()

      return random();


      template <>
      uint64_t random_value<uint64_t>()
      uint32_t(random());



      And then inside RowArray::RowArray you would simply use:



      rowdata[i] = random_value<T>();


      To factor related specializations together (for example all integral types), take a look at std::enable_if.



      A second way you might do this is in C++17 is with if constexpr and std::is_same_v. For example, inside your RowArray::RowArray constructor, you can do something like this:



      for (int i = 0; i < size; ++i)

      if constexpr (std::is_same_v<T, float>)
      row[i] = /* whatever you want for float case */
      else if constexpr (std::is_same_v<T, int>)
      row[i] = /* whatever you want for int case*/
      else
      static_assert(sizeof(T) == 0, "unsupported type");



      Take a look at the type_traits header to see how to test for all integral types etc.



      Finally, take a look at C++ random library http://www.cplusplus.com/reference/random/ to avoid making common mistakes when working with random values.






      share|improve this answer

























        0












        0








        0







        Not entirely clear from your question, but assuming you want to generate random values in different ways for different types, you can use specialization of a template function:



        template <class T>
        T random_value(); // no definition

        template <>
        float random_value<float>()

        return float(random()) / RAND_MAX; // number in [0, 1)


        template <>
        int random_value<int>()

        return random();


        template <>
        uint64_t random_value<uint64_t>()
        uint32_t(random());



        And then inside RowArray::RowArray you would simply use:



        rowdata[i] = random_value<T>();


        To factor related specializations together (for example all integral types), take a look at std::enable_if.



        A second way you might do this is in C++17 is with if constexpr and std::is_same_v. For example, inside your RowArray::RowArray constructor, you can do something like this:



        for (int i = 0; i < size; ++i)

        if constexpr (std::is_same_v<T, float>)
        row[i] = /* whatever you want for float case */
        else if constexpr (std::is_same_v<T, int>)
        row[i] = /* whatever you want for int case*/
        else
        static_assert(sizeof(T) == 0, "unsupported type");



        Take a look at the type_traits header to see how to test for all integral types etc.



        Finally, take a look at C++ random library http://www.cplusplus.com/reference/random/ to avoid making common mistakes when working with random values.






        share|improve this answer













        Not entirely clear from your question, but assuming you want to generate random values in different ways for different types, you can use specialization of a template function:



        template <class T>
        T random_value(); // no definition

        template <>
        float random_value<float>()

        return float(random()) / RAND_MAX; // number in [0, 1)


        template <>
        int random_value<int>()

        return random();


        template <>
        uint64_t random_value<uint64_t>()
        uint32_t(random());



        And then inside RowArray::RowArray you would simply use:



        rowdata[i] = random_value<T>();


        To factor related specializations together (for example all integral types), take a look at std::enable_if.



        A second way you might do this is in C++17 is with if constexpr and std::is_same_v. For example, inside your RowArray::RowArray constructor, you can do something like this:



        for (int i = 0; i < size; ++i)

        if constexpr (std::is_same_v<T, float>)
        row[i] = /* whatever you want for float case */
        else if constexpr (std::is_same_v<T, int>)
        row[i] = /* whatever you want for int case*/
        else
        static_assert(sizeof(T) == 0, "unsupported type");



        Take a look at the type_traits header to see how to test for all integral types etc.



        Finally, take a look at C++ random library http://www.cplusplus.com/reference/random/ to avoid making common mistakes when working with random values.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 2:50









        Always ConfusedAlways Confused

        26526




        26526





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55054728%2fhow-to-generate-random-numbers-to-populate-a-dynamic-array-according-to-the-temp%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived