Gabriel Zuniga
Gabriel Zuniga

Reputation: 45

Fixing vector issue - Finding middle element of vector - C++

I'm trying to code an efficient method to which :

The maximum number of list values for any test case should not exceed 9. If exceeded, output "Too many numbers".

I have the solution down for finding the middle number in a vector, but can't figure out a way to detect if the values received are more than 9.

Obviously the vector will never be more than 9 since the vector gets resized in the loop and was wondering if anyone could guide me through a work around! Thank you in advance!

Task description:

Given a sorted list of integers, output the middle integer. A negative number indicates the end of the input (the negative number is not a part of the sorted list). Assume the number of integers is always odd.

The maximum number of list values for any test case should not exceed 9. If exceeded, output "Too many numbers".

Input: 2 3 4 8 11 -1

Output: Middle item: 4

Input: 10 20 30 40 50 60 70 80 90 100 110 -1

Output: Too many numbers

when input:

10 20 30 40 50 60 70 80 90 100 110 -1

is used, my output is:

Middle item: 50

instead of

Too many numbers

#include <iostream>
#include <vector>   // Must include vector library to use vectors
using namespace std;

int main() {
   const int NUM = 9;
   vector<int> numInts(NUM);
   int value;
   
   //fills loop in with values    
   for ( int i = 0; i < numInts.size(); ++i){
   cin >> value;
     if (value > 0){
     numInts.at(i) = value;
     
     }
     else{
     numInts.resize(i);
     break;
     }
   }
  
   //outputs vector if within size -- but will always be in size(need to fix)
   if (numInts.size() > 9){
   cout << "Too many numbers" << endl;
   }
   else{
   cout << "Middle item: " << numInts.at(numInts.size()/2) << endl;
   }
   return 0;
}

Upvotes: 0

Views: 505

Answers (1)

Badee Salloum
Badee Salloum

Reputation: 26

I tried to reimplement your code so it will work as you want. Ask me if you feel that this code doesn't seems right to you.

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> nums(10);
    int value=0;
    int numberOfElements=0;
    bool moreThanNine=false;
    while(cin>>value)
    {
        if(value==-1)
        {
            break;
        }
        else
        {
            numberOfElements++;
            if(numberOfElements>9)
            {
                moreThanNine=true;
            }
            else
            {
                nums.at(numberOfElements-1) = value;
            }
        }
    }
    if(moreThanNine)
    {
        cout << "Too many numbers" << endl;
    }
    else
    {
        cout << "Middle item: " << nums.at(numberOfElements/2) << '\n';
    }
    return 0;
}

Upvotes: 1

Related Questions