Hello everyone. Im making a programm for "guess number game"
I have a little problem with vector.erase() and finding the mid position of a set of elements in a vector.
For example:
I have 10 numbers in a vector <int> (1, 2, 3, 4, 5, 6, 7, 8, 9, 10). Now I take the mid position and ask "Is your number equal or less than 5?"
If the answer is yes, the programm deletes a section and now the current values are (1, 2, 3, 4, 5), if not so the values are (6, 7, 8, 9, 10).
Im trying to do this in code but I am failing. I think that I have the problem because i am using .erase() in a incorrectly way.
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
|
int main()
{
vector <int> numbers;
char answer_key;
for (int i = 1; i <= 100; ++i)
{
numbers.push_back(i);
}
int n_size = numbers.size(); // numero de elementos
/*. ....... */
if (n_size % 2 == 0) // Only if the number of elements is pair...
{
int mid = (n_size / 2) - 1; // Mid position of the set of values.
cout << "Is the number equal or less than " << numbers[numbers.size() / 2 - 1] << " (y / n)? "; // Ask for the mid value.
if (answer_key == 'y')
{
numbers.erase(mid + 1, numbers.end()); // DELETES THE VALUES BETWEEN [(n/2) + 1, n] for only use the first n/2 values.
}
else if (answer_key == 'n')
{
numbers.erase(numbers.begin(), mid); //DELETES THE VALUES BETWEEN [1, n/2] for only use the values after n/2 + 1.
}
}
|
I would appreciate if someone would help me solve this problem.