my code is shown here:
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
using std::string;
using std::endl;
using std::cout;
using std::cin;
struct funcs
{
std::vector<int> values;
int sum;
void createVectorValues(){
while(values.size() < 100)
{
int x = rand() % 100;
values.push_back(x);
}
for(int& a : values)
{
sum = 1;
}
cout << sum;
}
};
int main()
{
srand;
funcs myFunct;
myFunct.createVectorValues();
}
the following code results in a large value such as -858993360
How can I change this code so that it can function properly
CodePudding user response:
You didn't define a constructor for
funcs
, so you get the default constructor, which invokes the default constructor of each member. This means theint
membersum
is left with an indeterminate value. See Does the default constructor initialize built-in types?. You probably want to write a constructor that initializessum
to0
.srand;
isn't a function call. It's valid syntax, becausesrand
evaluates to a pointer to thesrand
function, but it's an expression with no side effects, so it does nothing. Much as if you had written3;
. To call the function, you needsrand(arg)
, wherearg
is an appropriate integer. Or, switch to the C 11 random number generation features, which are much more powerful and usually have better randomness.
CodePudding user response:
Try this:
int main(int, char **) {
funcs myFunct;
myFunct.createVectorValues();
}
Although no idea why your antivirus is involved. That might be a separate issue.