Runtime Vector Error
Mar 23, 2017 at 11:07am UTC
Hello all,
I am trying to create a vector of integers of random size, and random numbers.
I have it working nicely when not nested within its own function. When I try to wrap it within its own function (with the goal of eventually being able to call it from its own class), I get a runtime error.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <vector>
int SystemSize();
std::vector<int > SystemData();
int main()
{
std::cout << SystemSize() << std::endl;
for (int i = 0; i < SystemData().size(); i++)
{
std::cout << SystemData()[i] << std::endl;
}
}
int SystemSize()
{
srand(time(NULL));
int Size = rand() % 10 + 1; //number between 1 and 10
return Size;
}
std::vector<int > SystemData()
{
int Size = SystemSize();
for (int i = 0; i < Size; i++) {
int Seed = rand() % 5 + 0; //number between 1 and 5
SystemData().push_back(Seed);
}
return std::vector<int >();
}
Last edited on Mar 23, 2017 at 11:08am UTC
Mar 23, 2017 at 11:18am UTC
SystemData() returns always an empty temporary vector that is discarded as soon as the function is done.
On line 36 you create an infinite recursion which will crash your program.
Mar 26, 2017 at 3:47pm UTC
Thanks so much for your help! I made a temporary vector within SystemData and used it as the return value and that seemed to do the trick.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
std::vector<int > SystemData()
{
int Size = SystemSize();
std::vector<int > System;
for (int i = 0; i < Size; i++) {
int Seed = rand() % 5 + 0; //number between 1 and 5
System.push_back(Seed);
}
return System;
}
Topic archived. No new replies allowed.