Hi, I'm having trouble writing a class called potential. I want to initialize it with a vector of integers such that
1) it creates an array of random numbers
2) the length of the array is equal to the product of the integers
So here's my code
potential.cpp
#include <vector>
#include "variable.h"
#include "potential.h"
#include "uniform.h"
using std::vector;
potential::potential(vector<int> vars){
int size = 1;
for(vector<int>::const_iterator iter = vars.begin(); iter != vars.end(); ++iter)
size = size*(*iter);
seed();
for(int i = 0; i < size; i++)
values.push_back(unif());
}
potential.h
#include <vector>
class potential {
public:
potential(std::vector<int>);
std::vector<double> getValues() const {return values;}
private:
std::vector<double> values;
};
My code to test the potential class, test_potential.cpp
#include <iostream>
#include <vector>
#include "potential.h"
#include "uniform.h"
using std::cin;
using std::cout;
using std::endl;
using std::vector;
int main(){
cout << "Please enter the number of states of your variables ";
int states = 0;
vector<int> variables;
while(cin >> states){
variables.push_back(states);
}
potential x(variables);
for(vector<double>::iterator iter = x.getValues().begin(); iter != x.getValues().end(); iter++){
cout << *iter << endl;
}
return 0;
}
The uniform.h is just a header file for various uniform random number generators.
#include <cstdlib>
#include <cmath>
#include <ctime>
#include "uniform.h"
using namespace std;
double unif(){
return rand() / double(RAND_MAX);}
double unif(double a, double b){
return (b - a)*unif() + a;
}
void seed(){
srand(time(0));
}
Now when I try ~/Documents/Programming$ ./test_potential Please enter the number of states of your variables 2 3 n
I get
0.812538 0.883743 0.283997 0.611596 0.965395 0.75795
so it seems to work fine. Now when I try ~/Documents/Programming$ ./test_potential Please enter the number of states of your variables 9 n
It seems to go through a large loop of zeros and then I get a segmentation fault. Any ideas why I'm having this problem? I'm really rather confused so any help would be appreciated.