简体   繁体   中英

vector not taking input from cin

I am trying to take input elements from cin as cin>>ngarmy[]i but all elements remains zero throughout the whole program can anyone tell me whats wrong with the vector ?

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector <int> ngarmy(100);
vector <int> nmarmy(100);
int main() {
    int t;
    cin >> t;
    while (t--) {
        int ng, nm;
        cin >> ng >> nm;
        for (int i = 0; i < ng; i++) {
            cin >> ngarmy[i];
        }
        for (int i = 0; i < nm; i++) {
            cin >> nmarmy[i];
        }
        sort(ngarmy.begin(), ngarmy.end());
        sort(nmarmy.begin(), nmarmy.end());
        int i = 0, j = 0;
        int ans = 0;
        while (1) {
            if (ngarmy[i] < nmarmy[j]) {
                i++;
                if (i == ng) {
                    ans = 1;
                    break;
                }
            }
            else {
                j++;
                if (j == nm) {
                    ans = 2;
                    break;
                }
            }

        }
        if (ans == 1)
            cout << "MechaGodzilla" << endl;
        else
            cout << "Godzilla" << endl;
    }
}

The vectors are size 100 but are mostly zeros because you don't have 100 inputs. When you sort the vectors all the zeros come to the start of the vectors because zero is the smallest number.

You are reading the vectors wrongly. Instead of having the vectors always size 100 you should make them the same size as the number of inputs you have. Start the vectors at size zero and use push_back to increase the size of the vector when you read a number.

Like this

vector <int> ngarmy; // vectors are size zero
vector <int> nmarmy;

    for (int i = 0; i < ng; i++) {
        int n;
        cin >> n;
        ngarmy.push_back(n); // add n to the vector
    }
    for (int i = 0; i < nm; i++) {
        int n;
        cin >> n;
        nmarmy.push_back(n); // add n to the vector
    }

Or as is suggested in the comments, you could just resize the vectors to the right size

vector <int> ngarmy;
vector <int> nmarmy;

    ngarmy.resize(ng);
    for (int i = 0; i < ng; i++) {
        cin >> ngarmy[i];
    }
    nmarmy.resize(nm);
    for (int i = 0; i < nm; i++) {
        cin >> nmarmy[i];
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM