Stuck with Vectors and Recursive Functions

Hey, I'm new to the forum and C++ so thanks in advance for yout help :3

i'm stuck with this programm, because I get a Core dumped error at the end (maybe because I access memory which was not initialized?)
i have to use vectors and recursive functions to write this one. It should read in values and input them in a vector (max. 90 inputs) if the value was already typed in it should ask the user to input the value for this position again until it's a non used value.



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
#include <iostream>
#include <string>
#include <vector>
using namespace std;

bool compare (int, vector <int> , int );

int main()
{
   vector <int> s;
   int count {0};
   int input {0};
   cout << "Input Value: "<< endl;
   cin >> input;
   s.push_back(input);
while (count <90)
{
   cout << "Input Value: " << endl; 
   cin >> input;
  if (compare (input, s, count)) {s.push_back(input);  count++ ;} 
  else{cout<< "Already existing Value "<< endl;}
}
return 0;
}

bool compare (int input, vector <int> s, int count)
{
    { 
    if (input == s.at (count))
        {return false;}
    if (count ==0) 
        {return true;}
    if ( count >0 && compare(input, s, count--))
        {return true;}
    }
}
Last edited on
What input that causes the problem?
The third input.
in main before the while it works.
the first function call that inputs the second value for the vector works (and also checks if it's the same value as the first input)
After the third input I get this error and my programm terminates.
So I guess the error happens in the recursive function line 33
Line 33:
 
    if ( count >0 && compare(input, s, count--))

count-- should be --count

Also the compiler issues a warning, if the condition at line 33 is not true, execution reaches the end of the function without returning a value.

You need to make sure the function will always return a specific value, you could add an arbitrary return true; or return false; when you are sure that line will never be reached. But if you do so, then add a message, such as std::cout << "\nthis line should never be reached\n"; just as an alert if something goes wrong.

As well as that, the proper fix is to change line 33 to:
1
2
    if (count > 0)
        return compare(input, s, --count);

That solved the problem thx a lot :D
Topic archived. No new replies allowed.